I want to access nested JSON object values by iterating. This is the data I get from my query:
{"_id":"654d4224fb04863b8eb89200","firms":[{"_id":["65423d5c240388c1594e7b7b"],"name":["Camaro Coiled Tubing"]}]}
{"_id":"654d4224fb04863b8eb8920d","firms":[{"_id":["65423d5c240388c1594e7b82"],"name":["DANCO Coiled Tubing"]}]}
{"_id":"654d4224fb04863b8eb8921b","firms":[{"_id":["65423d5c240388c1594e7b7d"],"name":["San Joaquin Bit"]}]}
I would like to create a second array with only the firm and name and have tried the following:
vendorList.forEach(function (d) {
vendorArray.push({
id: d.firms._id,
name: d.firms.name,
});
});
My output looks like this:
Vendor List: [{}, {}, {}, {}]
An empty array.
3
Answers
First of all your vendorList array is wrong.
then did the traversal same as your code,but id & name are at first index of firms so made the changes as per it.
Final output:
Assuming your data is actually an array of objects you can use
flatMap
andmap
to return the values embedded in the nested objects/arrays.