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 badges4 Answers
Reset to default 15Wrap 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);