I have an array that looks something like this:
[ { Id:1, Name:'' }, { Id:2, Name:'' }, { Id:2, Name:'' } ]
I want a result object that looks like this:
{ Id:[1, 2, 3] }
How do I achieve this in Javascript?
I have an array that looks something like this:
[ { Id:1, Name:'' }, { Id:2, Name:'' }, { Id:2, Name:'' } ]
I want a result object that looks like this:
{ Id:[1, 2, 3] }
How do I achieve this in Javascript?
Share Improve this question asked Feb 4, 2019 at 10:08 amitairosamitairos 2,97713 gold badges51 silver badges86 bronze badges 2- 1 Possible duplicate of From an array of objects, extract value of a property as array and Returning only certain properties from an array of objects in Javascript and Typescript Select Ids from object – adiga Commented Feb 4, 2019 at 10:12
- @adiga I searched and looked up multiple posts, but apparently I didn't know how to phrase my question so I didn't find the answer to it. – amitairos Commented Feb 4, 2019 at 10:25
2 Answers
Reset to default 4You can create an Object Literal and use Array.prototype.map() to get ids array to fulfill the Id
property.
Code:
const data = [ { Id: 1, Name:'' }, { Id: 2, Name:'' }, { Id: 3, Name:'' } ]
const result = { Id: data.map(obj => obj.Id) };
console.log(result);
const array = [ { Id:1, Name:'' }, { Id:2, Name:'' }, { Id:2, Name:'' } ];
console.log({Id: array.map(element => element.Id)})