转: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);
有志者,事竟成,破釜沉舟,百二秦关终属楚; 苦心人,天不负,卧薪尝胆,三千越甲可吞吴。