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

JavaScript map - select one property from array with name - Stack Overflow

programmeradmin3浏览0评论

I have this array:

[{a: 1, b: 2}, {a: 2, b: 3}, {a: 3, b: 1},...]

and I would like to convert to this array:

[{a:1}, {a:2}, {a: 3}]

I tried this:

array.map(x => {'a': x.a}) 

but this is a mistake (its giving error). is there any function in JavaScript that can do this? Thanks

I have this array:

[{a: 1, b: 2}, {a: 2, b: 3}, {a: 3, b: 1},...]

and I would like to convert to this array:

[{a:1}, {a:2}, {a: 3}]

I tried this:

array.map(x => {'a': x.a}) 

but this is a mistake (its giving error). is there any function in JavaScript that can do this? Thanks

Share Improve this question edited Jan 17, 2018 at 8:37 Nemani 7846 silver badges12 bronze badges asked Jan 17, 2018 at 6:38 bluraybluray 1,9536 gold badges39 silver badges72 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 15

Wrap implicitly returned object with parenthesis and use the return value of array.map:

let array = [{a: 1, b: 2}, {a: 2, b: 3}, {a: 3, b: 1}];
array = array.map(x => ({'a': x.a}));
console.log(array);

And even shorter with ES6 destructuring and shorthand object litteral:

let array = [{a: 1, b: 2}, {a: 2, b: 3}, {a: 3, b: 1}];
array = array.map(({a}) => ({a}));
console.log(array);

You were almost there, just wrap that expression in ()

map(x => ({'a': x.a}))

Demo

var output = [{a: 1, b: 2}, {a: 2, b: 3}, {a: 3, b: 1}].map(x => ({'a': x.a}));

console.log(output);

[{a: 1, b: 2}, {a: 2, b: 3}, {a: 3, b: 1}].map(element=>({'a': element.a}))

I would like to convert to this array...

If you do not require to create a separate array, it would be better to use .forEach and remove the property b from the objects.

var arr = [{
  a: 1,
  b: 2
}, {
  a: 2,
  b: 3
}, {
  a: 3,
  b: 1
}];

arr.forEach(function(x) {
  delete x.b;
});

console.log(arr);

发布评论

评论列表(0)

  1. 暂无评论