-4

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?

amitairos
  • 2,907
  • 11
  • 50
  • 84
  • Possible duplicate of [From an array of objects, extract value of a property as array](https://stackoverflow.com/questions/19590865) and [Returning only certain properties from an array of objects in Javascript](https://stackoverflow.com/questions/24440403) and [Typescript Select Ids from object](https://stackoverflow.com/questions/41197546) – adiga Feb 04 '19 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 Feb 04 '19 at 10:25

2 Answers2

5
const array = [ { Id:1, Name:'' }, { Id:2, Name:'' }, { Id:2, Name:'' } ];
console.log({Id: array.map(element => element.Id)})
Krzysztof Krzeszewski
  • 5,912
  • 2
  • 17
  • 30
5

You 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);
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46