Lets say I have:

const arr = [
  {label: 1, value: "One"},
  {label: 2, value: "two"}
}

I want to get value out of it as an arrar of string,

Traditional way:

const strArr = [];
arr.forEach(ele => {strArr.push(ele.value)});
console.log(strArr);

But can I do it using spread operator or any other way ?

4 Answers

3
Pranav C Balan On Best Solutions

You can use Array#map method.

const arr = [{
    label: 1,
    value: "One"
  },
  {
    label: 2,
    value: "two"
  }
]

let res = arr.map(o => o.value)
// or in case you want to create an object with only value 
// property then you can use Destructuring
// .map(({ value }) => ({ value }))

console.log(res)

1
Maheer Ali On

You can't do it using spread operator. Use map() instead.

const arr = [{label: 1, value: "One"}, {label: 2, value: "two"}]

const res = arr.map(x => x.value);
console.log(res)

2
Nick Parsons On

You could use Array.from by defining a mapping function:

const arr = [
  {label: 1, value: "One"},
  {label: 2, value: "two"}
];

const vals = Array.from(arr, o => o.value);
console.log(vals);

1
adam.k On

I would use .map() in this case as well. But if you really wanted to use a spread operator you could do this.

const arr = [
  {label: 1, value: "One"},
  {label: 2, value: "two"}
];

const res = []

for (let obj of arr) {
  res = [...res, obj.value]
}
console.log(res)