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)
但是我可以使用扩展运算符或任何其他方式来做到这一点吗?
您可以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)
在这种情况下,我也会使用 .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)
可以用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)
| 归档时间: |
|
| 查看次数: |
2610 次 |
| 最近记录: |