我试图将一个对象添加到另一个对象。
我们说我有两个对象。 selectedItemObj
和selectedItemQueue
。我想将selectedItemObj
添加到selecteditemQueue
,但只有selectedItemObject
与selectedItemQueue
我们在这里说我有这个对象:
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();
};
}
答案 0 :(得分:0)
这样的事情@JsBIN怎么样?我假设market_hash_name
用于区分每个对象。
var selecteditemObj = [
{
"market_hash_name":"Chroma 2 Case Key 1",
}
];
var selectedItemQueue = [
{
"market_hash_name":"Chroma 2 Case Key 2",
},
{
"market_hash_name":"Chroma 2 Case Key 3",
}
];
function addItemObjIfNotExist(obj1, obj2, id) {
for(var i = 0, len = obj2.length; i < len; i++) {
if(obj1[1][id] !== obj2[i][id]) {
obj2.push(obj1);
}
}
return obj2;
}
console.log(addItemObjIfNotExist(selectedItemQueue,selecteditemObj, 'market_hash_name'));
Output
:
[[object Object] {
market_hash_name: "Chroma 2 Case Key 1"
}, [[object Object] {
market_hash_name: "Chroma 2 Case Key 2"
}, [object Object] {
market_hash_name: "Chroma 2 Case Key 3"
}]]
答案 1 :(得分:0)
我会这样做:
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);
对我来说效果很好!