Reputation: 21
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 ?
Upvotes: 1
Views: 93
Reputation: 20039
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)
Upvotes: 5
Reputation: 32148
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()}]`)
Upvotes: 4
Reputation: 6731
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.
Upvotes: 0
Reputation: 7446
Use 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);
Upvotes: 2
Reputation: 15519
iterate over the array and concatenate the values into a new common array.
const obj = [{x:150, y:260},{x:160, y:545},{x:478, y:858},{x:125, y:560}];
let arr =[];
obj.forEach(function(item){
arr = arr.concat(Object.values(item));
})
console.log(arr)
Upvotes: 1
Reputation: 915
try this:
[{x:150, y:260},{x:160, y:545},{x:478, y:858},{x:125, y:560}].flatMap(obj => [obj.x,obj.y])
Upvotes: 2