扩展运算符以获取数组内对象的单个属性 - JS/TS

Use*_*614 3 javascript typescript ecmascript-6

可以说我有:

const arr = [
  {label: 1, value: "One"},
  {label: 2, value: "two"}
}
Run Code Online (Sandbox Code Playgroud)

我想value摆脱它的束缚,

传统方式:

const strArr = [];
arr.forEach(ele => {strArr.push(ele.value)});
console.log(strArr);
Run Code Online (Sandbox Code Playgroud)

但是我可以使用扩展运算符或任何其他方式来做到这一点吗?

Nic*_*ons 5

您可以Array.from通过定义映射函数来使用:

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

const vals = Array.from(arr, o => o.value);
console.log(vals);
Run Code Online (Sandbox Code Playgroud)


ada*_*m.k 5

在这种情况下,我也会使用 .map() 。但是如果你真的想使用扩展运算符,你可以这样做。

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

const res = []

for (let obj of arr) {
  res = [...res, obj.value]
}
console.log(res)
Run Code Online (Sandbox Code Playgroud)

  • 一个挑剔:“const res = []”应该是“let”,因为它在实例化下面被更改。否则这效果很好! (2认同)

Pra*_*lan 4

可以用Array#map方法。

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)
Run Code Online (Sandbox Code Playgroud)

  • 或者更好的 `arr.map(v => v.value)` <- 解构完全没有意义的情况之一。 (3认同)