I have a part of code that looks like this where I need to pick objects out of array of objects and push them into an array.
var issues = await Issues.find({})
console.log(issues)
let issuesData = [];
for (issue of issues) {
console.log(issue)
issuesData.push(issue['data'])
}
The output of issues
is
[
{
_id: new ObjectId("6346e32032eae0a8d1986bf0"),
data: { no: 1, date: '31-10-2022', cover: 'path/to/cover/image' },
articles: [ [Object], [Object] ],
letters: [ [Object], [Object] ]
},
{
_id: new ObjectId("6346e37c32eae0a8d198a3bf"),
data: { no: 2, date: '31-12-2022', cover: 'path/to/cover/image' },
articles: [ [Object], [Object] ],
letters: [ [Object], [Object] ]
}
]
and in issuesData
I want an array like
[ { no: 1, date: '31-10-2022', cover: 'path/to/cover/image' }, { no: 2, date: '31-12-2022', cover: 'path/to/cover/image' } ]
but I get an undefined when I push issue['data']
CodePudding user response:
I tried and it seems working fine for me. However a better way is to remove the for loop
and replace it with let issuesData = issues.map(issue => issue.data)
to get the same expected output.
CodePudding user response:
You can simply apply the map function which will take care of your problem.
Try this:
const data = [
{
_id: "6346e32032eae0a8d1986bf0",
data: { no: 1, date: '31-10-2022', cover: 'path/to/cover/image' },
articles: [],
letters: []
},
{
_id: "6346e37c32eae0a8d198a3bf",
data: { no: 2, date: '31-12-2022', cover: 'path/to/cover/image' },
articles: [],
letters: []
}
];
const issuesData = data.map(item => item.data);
console.log(issuesData);
map() creates a new array from calling a function for every array element. map() calls a function once for each element in an array.