Reputation: 1963
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
Upvotes: 4
Views: 16989
Reputation: 3687
[{a: 1, b: 2}, {a: 2, b: 3}, {a: 3, b: 1}].map(element=>({'a': element.a}))
Upvotes: 1
Reputation: 13356
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);
Upvotes: 15
Reputation: 14541
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);
Upvotes: 0
Reputation: 68393
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);
Upvotes: 6