I have an object like this :
obj = [{x:150, y:260},{x:160, y:545},{x:478, y:858},{x:125, y:560}]
and I want an array like this:
array = [150,260,160,545,478,858,125,560]
How can I do ?
Using flatMap()
const obj = [{x:150, y:260},{x:160, y:545},{x:478, y:858},{x:125, y:560}]
const res = obj.flatMap(Object.values)
console.log(res)
... .flatMap(Object.values) already is sufficient ... no need for the additional callback.You can use Array.prototype.reduce
const obj = [{x:150, y:260},{x:160, y:545},{x:478, y:858},{x:125, y:560}]
const arr = obj.reduce((acc, {x, y}) => acc.concat(x, y), [])
document.write(`arr = [${arr.join()}]`)
as suggested in the comments to make it more generic you can
const obj = [{v: 100, x:150, y:260, z: 123},{x:160, y:545},{x:478, y:858},{x:125, y:560}]
const arr = obj.flatMap(Object.values)
document.write(`arr = [${arr.join()}]`)
concat. Would there be any relevant difference instead of using push and returning the same array instead? that would be an interesting scenario..push may have smaller memory usage, but with .concat is shorter because it returns the resulting arrayUse reduce to make it in a single iteration. Otherwise, you can use map and flat or really many others, like flatMap.
Differently from map + flat or flatMap, reduce iterates the original array only once.
This likely is irrelevant in most scenarios, unless the array you're going to iterate is somewhat big.
const obj = [{x:150, y:260},{x:160, y:545},{x:478, y:858},{x:125, y:560}];
const array = obj.reduce((acc, next) => {
acc.push(...Object.values(next));
return acc;
}, []);
console.log(array);
In ES6 you can implement the following way using reduce and object destruction and array destruction:
const collection = [{x:150, y:260},{x:160, y:545},{x:478, y:858},{x:125, y:560}]
const arr = collection.reduce((acc, {x, y}) => [...acc, x, y], [])
console.log(arr)
I'd say it is a collection not an object, so let's name it to collection not obj.
x?
[{x:150, y:260},{x:160, y:545}].reduce((collector, item) => collector.concat(Object.values(item)), []);... making use ofObject.valuesandArray.prototype.concat