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?
const array = [ { Id:1, Name:'' }, { Id:2, Name:'' }, { Id:2, Name:'' } ];
console.log({Id: array.map(element => element.Id)})
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);
Try this:
var arr = [ { Id:1, Name:'' }, { Id:2, Name:'' }, { Id:2, Name:'' } ]
var Ids = arr.map(function(param){
return param.Id
});
var obj = {Id: Ids}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.