Reputation: 15
i would like to get the "-lists" data from an array with several objects:
[{...},{...},{...},{"-name": "Test", "-lists": [123, 456, 789]},{...}]
i tried with a filter function but it doesnt works :-(
this is the query where i would like to change the result to the value/array of "-lists"
.findOne({ _id: serviceID }, function (err, result) {
if (err) {
res.json(err);
} else {
try{
res.json(result.service.modules)
console.log(result.service.modules)
}catch(error){
console.log(error)
}
}
})
Have someone an idea for me?
Best regrads & stay healthy
Upvotes: 0
Views: 51
Reputation: 435
This is an example of one of the approaches you can use to extract the value of an array nested in an object which is inside an array.
const arr = [{ someValue: 1 }, { "-lists": [1, 2, 3] }];
const result = [];
arr.filter((val) => {
if (val["-lists"]) {
result.push(...val["-lists"]);
}
});
console.log(result);
Upvotes: 1
Reputation: 1729
You can try the map
function of the array.
const data = [
{"-name": "Test", "-lists": [123, 456, 789]},
{"-name": "Test", "-lists": [222, 333, 444]}
];
const result = data.map((x) => x['-lists']);
console.log(result);
This will return an array of the lists data which is an array in itself.
Upvotes: 1