0

Is there a way to unpack values from an array of objects using destructuring assigments?

[

{a : 1},
{a : 1},
{a : 1},
{a : 1}

]

The result I need here is an array: [1,1,1,1]

5 Answers 5

1

Destructuring that would require the creation of 4 separate variables which would then get recombined into an array later. It would be very WET, and wouldn't make much sense, but if you had to:

const arr = [
  {a : 1},
  {a : 1},
  {a : 1},
  {a : 1}
]
const [{ a: item1 }, { a: item2 }, {a: item3}, {a: item4 }] = arr;
const newArrOfAs = [item1, item2, item3, item4];
console.log(newArrOfAs);

Your original code using reduce is better, but even more appropriate would be to use Array.prototype.map, since the input array and output array's items are one-to-one:

const arr = [
  {a : 1},
  {a : 1},
  {a : 1},
  {a : 1}
]
const newArrOfAs = arr.map(({ a }) => a);
console.log(newArrOfAs);

Sign up to request clarification or add additional context in comments.

1 Comment

seems like that makes no sense if the array is longer than that. I think array.map is then the best solution. Really thought of using reduce combined with this {} but was just a pseudo code idea. Thank you
0

You would use .map():

const a = [

  {
    a: 1
  },
  {
    a: 1
  },
  {
    a: 1
  },
  {
    a: 1
  }

];


const b = a.map(val => val.a);

console.log(b);

Comments

0

This should work. You can use foreach or map

const array = [
  {a : 1},
  {a : 1},
  {a : 1},
  {a : 1}
]
let newArray = []
array.forEach(function(element) {
  newArray.push(element.a)
});
console.log(newArray)

Comments

0

You should just use map:

 

const arr = [
{a : 1},
{a : 1},
{a : 1},
{a : 1}
];

const res = arr.map(({ a }) => a);

console.log(res);

Comments

0

You could use the upcoming Array#flatMap

var array = [{ a: 1 }, { a: 1 }, { a: 1 }, { a: 1 }];
    result = array.flatMap(Object.values);

console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.