I want to get all not owned items from a player items array what i tried
var players = {
"player1": {
"items": [{
"item1": {
"owned": false,
"price": 3000,
},
"item2": {
"owned": true,
"price": 3000,
}
}]
}
}
Object.keys(players).forEach(player => {
for(var i =0; i < players[player].items.length; i++) {
var not_owned = players[player].items.filter(item => {return item.owned === false});
console.log(not_owned.length);
}
});
but it is not giving me anything i tried to see the length and it gives me 0,
i tried to console.log it without length and it gives me undefined any ideas?
You need to get the inner items object values and then filter it
var players = { "player1": { "items": [{ "item1": { "owned": false, "price": 3000, }, "item2": { "owned": true, "price": 3000, } }] } } Object.keys(players).forEach(player => { for(var i =0; i < players[player].items.length; i++) { var not_owned = Object.entries(players[player].items[i]).filter(([key, item]) => {return item.owned === false}); console.log(not_owned.length); } });
You don't need the for
loop in there. Now for every iteration of the forEach
the not owned will contain the items you want for this player.
var players = {
"player1": {
"items": [{
"item1": {
"owned": false,
"price": 3000,
},
"item2": {
"owned": true,
"price": 3000,
}
}]
}
}
Object.keys(players).forEach(player => {
var not_owned = players[player].items.filter(item => {return item.owned === false});
console.log(not_owned.length);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.