转:JS提取数组的某一属性组成新的数组

原博客地址: https://blog.csdn.net/u012732909/article/details/114996684

例:

 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"]

 方法一:

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

方法二:

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

方法二改进:

1 let arrnew = arrold.map((item,index) => {
2     return Object.assign({},{'name':item.name})
3 })

关于Object.assign(target,sources)方法:拷贝源对象且可枚举的属性到目标对象,如果目标对象中的属性具有相同的键,则属性将被源中的属性覆盖。例:

1 const object1 = { a: 1, b: 2, c: 3 }; 
2 // object2: a=1, b=2, c=3, d=5 
3 const object2 = Object.assign({c: 4, d: 5}, object1);
posted @ 2021-10-17 17:17  陆陆无为而治者  阅读(533)  评论(0编辑  收藏  举报