Given the following object array:
var myObject =
[
{X:1, Y:2, Z:3},
{X:4, Y:5, Z:6},
{X:7, Y:8, Z:9},
]
What is some elegant code to get the following output?:
var subset = [ Y:2, Y:5, Y:8 ]
const arr = [
{X:1, Y:2, Z:3},
{X:4, Y:5, Z:6},
{X:7, Y:8, Z:9},
];
const output = arr.map(({Y}) => ({Y})); // [{Y: 2}, {Y: 5}, {Y: 8}]
This uses an arrow function mapped over the array, destructures the Y property out of each item, and uses object property shorthand to return a new object with just the Y property for each item of the array.
arr.map(({Y})); return the value of Y or {Y:Y}? Enquiring minds want to know...map with an arrow function is fairly elegant:
var myObject =
[
{X:1, Y:2, Z:3},
{X:4, Y:5, Z:6},
{X:7, Y:8, Z:9},
];
var result = myObject.map(e => ({Y: e.Y}));
console.log(result);
Even more so if you add in some destructuring as Jared did. :-)
Depending on how reusable you want your code to be, I find it fairly elegant to add some currying :
const arr = [
{X:1, Y:2, Z:3},
{X:4, Y:5, Z:6},
{X:7, Y:8, Z:9},
];
const get = prop => o => ({[prop]: o[prop]});
const extract = arr => prop => arr.map(get(prop));
const result = extract(arr)('Y');
console.log(result);
var subset = [ Y:2, Y:5, Y:8 ]is invalid syntax. Do you mean:var subset = { Y1:2, Y2:5, Y3:8 }or do you mean:var subset = [ { Y:2 }, { Y:5 }, { Y:8 } ]? SInce the first one will usearray.reduce()and the second will usearray.map()