I have a list of ids as reference, and I have an object which contains multiple objects that have array of objects.
I want to make an array of objects with corresponding ids in the list, the FASTEST way.
const data = {
"items": {
"item1": [{
"id": "id1",
"info": "info1"
},
{
"id": "id2",
"info": "info22"
}
],
"item20": [{
"id": "id3",
"info": "info5"
}],
"item5": [{
"id": "id4",
"info": "info6"
},
{
"id": "id5",
"info": "info7"
}
]
}
};
const keep = ['id4', 'id2'];
const results = [];
keep.forEach(function(val) {
const match = Object.keys(data.items).map(item => {
return data.items[item].find(obj => obj.id === val)
});
results.push(match)
})
console.log('final: ', results)
the current is not returning what i want. the expected result will be:
[
{
"id": "id2",
"info": "info22"
},
{
"id": "id4",
"info": "info6"
}
]
update:
How about in the case if the data is itself an array of objects, and we want to do the same for each one?
const data = [{
"otherStuff": "otherB",
"items": {
"item1": [{
"id": "id1",
"info": "info1"
},
{
"id": "id2",
"info": "info22"
}
],
"item20": [{
"id": "id3",
"info": "info5"
}],
"item5": [{
"id": "id4",
"info": "info6"
},
{
"id": "id5",
"info": "info7"
}
]
}
}, {
"otherStuff": "otherA",
"items": {
"item1": [{
"id": "id1",
"info": "info10000"
},
{
"id": "id2",
"info": "info220000"
}
],
"item20": [{
"id": "id3",
"info": "info5000"
}],
"item5": [{
"id": "id4",
"info": "info60000"
},
{
"id": "id5",
"info": "info7000"
}
]
}
}];
const keep = ['id4', 'id2'];
const results = [];
keep.forEach(function(val) {
data.forEach(function(entry){
Object.keys(entry.items).forEach(item => {
var match = entry.items[item].find(obj => obj.id === val);
if (match) {
results.push(match)
}
});
});
})
console.log(results)
and the output should be:
[
{
"otherStuff": "otherB",
"items": [
{
"id": "id2",
"info": "info22"
},
{
"id": "id4",
"info": "info6"
}
]
},
{
"otherStuff": "otherA",
"items": [
{
"id": "id2",
"info": "info220000"
},
{
"id": "id4",
"info": "info60000"
}
]
}
]
the result is not the same though.