gpt4 book ai didi

javascript - 检查子对象是否存在,如果存在,则添加到对象

转载 作者:行者123 更新时间:2023-12-01 05:34:29 24 4
gpt4 key购买 nike

我正在尝试将一个对象添加到另一个对象。

假设我有两个对象。 selectedItemObjselectedItemQueue 。我想添加selectedItemObjselecteditemQueue但前提是 selectedItemObjectselectedItemQueue 中的任何对象都不匹配

假设我这里有这个对象:

var selecteditemObj = [
{
"market_hash_name":"Chroma 2 Case Key 1",
"assetid":"92700754417_143965972",
"amount":1,
"image":"https://steamcommunity-a.akamaihd.net/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXX7gNTPcUxuxpJSXPbQv2S1MDeXkh6LBBOie3rKFRh16PKd2pDvozixtSOwaP2ar7SlzIA6sEo2rHCpdyhjAGxr0A6MHezetG0RZXdTA/"
}];



var selectedItemQueue = [
{
"market_hash_name":"Chroma 2 Case Key 2",
"assetid":"92700754667_143865972",
"amount":1,
"image":"https://steamcommunity-a.akamaihd.net/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXX7gNTPcUxuxpJSXPbQv2S1MDeXkh6LBBOie3rKFRh16PKd2pDvozixtSOwaP2ar7SlzIA6sEo2rHCpdyhjAGxr0A6MHezetG0RZXdTA/"
},
{
"market_hash_name":"Shadow Case Key 3",
"assetid":"1293611210722_143865972",
"amount":1,
"image":"https://steamcommunity-a.akamaihd.net/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXX7gNTPcUxuxpJSXPbQv2S1MDeXkh6LBBOiePrKF4wi6aaIGwStN_jl4bSzvXwMO6AwDlSvsYoiOiZ8dij3QbtqkU9ZnezetFWWxusZg/"
},
{
"market_hash_name":"Shadow Case Key 4",
"assetid":"123393510722_143861972",
"amount":1,
"image":"https://steamcommunity-a.akamaihd.net/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXX7gNTPcUxuxpJSXPbQv2S1MDeXkh6LBBOiePrKF4wi6aaIGwStN_jl4bSzvXwMO6AwDlSvsYoiOiZ8dij3QbtqkU9ZnezetFWWxusZg/"
}
];

这是我的尝试,它添加到队列中,但不检查子对象是否存在。我怎样才能添加它?

function addItemToSelectedQueue(assetId){
var itemObj = findItemById(assetId);
var queueHasItem = false;
for (var i = selectedItemQueue.length - 1; i >= 0; i--) {
if (selectedItemQueue[i] === itemObj) {
queueHasItem == true;
};
};
if (queueHasItem == false) {
selectedItemQueue.push(itemObj);
updateSelecteditems();
};
}

最佳答案

我会这样做:

function addItemToSelectedQueue(fromobj, toobj){
var found = false;
for(var x=0; x<toobj.length; x++){
if(toobj[x].market_hash_name == fromobj[0].market_hash_name){
found = true;
}
}

if(found == false){
toobj.push(fromobj[0]);
}
}

用法:

addItemToSelectedQueue(selecteditemObj, selectedItemQueue);

对我来说工作得很好!

关于javascript - 检查子对象是否存在,如果存在,则添加到对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34880794/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com