Javascript Merge multiple object values into array - Stack Overflow

I have an array that looks something like this:[ { Id:1, Name:'' }, { Id:2, Name:''

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
Add a ment  | 

2 Answers 2

Reset to default 4

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);

const array = [ { Id:1, Name:'' }, { Id:2, Name:'' }, { Id:2, Name:'' } ];
console.log({Id: array.map(element => element.Id)})

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745381159a4625232.html

相关推荐

  • Javascript Merge multiple object values into array - Stack Overflow

    I have an array that looks something like this:[ { Id:1, Name:'' }, { Id:2, Name:''

    20小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信