js提取对象数组中的某一个属性组成新数组

例:

 1 arrold = [
 2  
 3   {name: "name1", age: "1"},
 4   {name: "name2", age: "2"},
 5   {name: "name3", age: "3"},
 6   {name: "name4", age: "4"},
 7   {name: "name5", age: "5"},
 8   {name: "name6", age: "6"}
 9 ]
10  
11 arrnew = ["name1","name2","name3","name4","name5","name6"]

 

方法一:

let arr = [];
arrold.forEach(e => { 
    arrnew.push(e.name)
})

 

方法二:

let arrnew = arrold.map((obj,index) => {
    return obj.name;
}).join(",").split(',')

 

方法二改进:

let arrnew = arrold.map((item,index) => {
    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);

 

posted @ 2022-11-24 09:23  曲琦  阅读(6938)  评论(0编辑  收藏  举报