JavaScript 中循环数据、改变数据的几种方法 示例

一、将数组转为数组对象

let arr = ["张三","李四","王五","赵六"]
let obj = {}
 
// 将数组转化为对象
for (let key in arr) {
   obj[key] = arr[key];
};
 
newArray = Object.keys(obj).map(val => ({
    label: obj[val]
}))
 
console.log(newArray) // [{label: '张三'},{label: '李四'},{label: '王五'},{label: '赵六'}]

二、将数组对象中的属性值取出并组成新的数组

let arr = [ 
  {name: "张三", age: "1", sex: "男", grade: 11},
  {name: "李四", age: "2", sex: "男", grade: 12},
  {name: "王五", age: "3", sex: "男", grade: 13},
  {name: "赵六", age: "4", sex: "男", grade: 16},
]
 
let res = arr.map((item,index) => {
    return Object.assign({},{'name':item.name,'grade':item.grade})
})
 
console.log(res)
// 输出结果为 [{name: '张三', grade: 11},{name: '李四', grade: 12},{name: '王五', grade: 13}, {name: '赵六', grade: 16}]

三、将数组对象中的属性值取出并组成新的数组

let arr = [ 
  {name: "张三", age: "1", sex: "男", grade: 11},
  {name: "李四", age: "2", sex: "男", grade: 12},
  {name: "王五", age: "3", sex: "男", grade: 13},
  {name: "赵六", age: "4", sex: "男", grade: 16},
]
 
let res = arr.map((item,index) => {
    return item.grade;
})
 
console.log(res) // 输出结果为 [11, 12, 13, 16]

向数组对象中的所有对象添加属性

let resultList = [{"name":"张三"},{"name":"李四"}]
 
resultList.forEach(tem => {
    tem.age = 18;
})
 
console.log(resultList) // [{name: '张三', age: 18}, {name: '李四', age: 18}]
posted @ 2023-04-19 14:03  打个大大西瓜  阅读(776)  评论(0编辑  收藏  举报