js获取对象数组中指定属性值的新数据
2024/1/29
例:
let arr = [
{name: "name1", age: "1",type:"1"},
{name: "name2", age: "2",type:"2"},
{name: "name3", age: "3",type:"3"},
]
let list = ["name1","name2","name3"]
方法一:
arr.forEach(e => {
list.push(e.name)
})
方法二:
list = arr.map(v => {
return v.name;
})
如果用for循环包括forEach,map循环是取不出来单独想要的属性,需要借助Object.assign方法
list = arr.map((item) => {
return Object.assign({}, { name: item.name, age: item.age})
})
//[{name: "name1", age: "1"},{name: "name2", age: "2"},{name: "name3", age: "3"}]
关于Object.assign(target,sources)方法:拷贝源对象且可枚举的属性到目标对象,如果目标对象中的属性具有相同的键,则属性将被源中的属性覆盖。