js提取对象数组中的某一个属性组成新数组
示 例
arrOld = [
{name: "zhangsan", age: "18"},
{name: "lisi", age: "20"},
{name: "wangwu", age: "17"},
{name: "zhaoliu", age: "19"}
]
arrNew = ["zhangsan", "lisi", "wangwu", "zhaoliu"]
方法一:
let arrNew = []
arrOld.forEach(item => {
arrNew.push(item.name)
})
方法二:
let arrNew = arrOld.map(item => {
return item.name;
})
补充:
let arrNew = arrOld.map(item => {
return Object.assign({},{'name':item.name})
})
关于Object.assign(target,sources)方法:拷贝源对象且可枚举的属性到目标对象,如果目标对象中的属性具有相同的键,则属性将被源中的属性覆盖。示例:
const object1 = {
a: 1,
b: 2,
c: 3
};
// object2: a=1, b=2, c=3, d=5
const object2 = Object.assign({c: 4, d: 5}, object1);
欢迎交流!