最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript Merge multiple object values into array - Stack Overflow

programmeradmin1浏览0评论

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)})
发布评论

评论列表(0)

  1. 暂无评论