map 重构数组获取数组对象中某一字段组成新数组或者更改属性名字段返回新数组

一:取数组对象中的某一字段组成新数组

原数组对象:

[   //data的数据
	{ "txt":"a","codId":"1","id":1},
	{ "txt":"b","codId":"1","id":2},
	{ "txt":"c","codId":"1","id":3}
]

希望得到:

['a', 'b', 'c']

实现方法:

let time = data.map(item =>(item.txt))
console.log(time) 
//控制台输出如下
//['a', 'b', 'c']


二:取数组对象的某些字段重命名并组成新数组

希望得到:

[   //data的数据
	{ "name":"a"},
	{ "name":"b"},
	{ "name":"c"}
]

实现方法:

let resion = data.map(item =>({ name: item.txt}))
console.log(resion) 
//控制台输出
[   //data的数据
	{ "name":"a"},
	{ "name":"b"},
	{ "name":"c"}
]
let resion= data.map(item =>({ name: item.txt + item.id}))
console.log(resion) 
//控制台输出
[   //data的数据
	{ "name":"a1"},
	{ "name":"b2"},
	{ "name":"c3"}
]
let resion= data.map(item =>({ name: item.txt + item.id,,id:item.id}))
console.log(resion) 
//控制台输出
[   //data的数据
	{ "name":"a1","id":1},
	{ "name":"b2","id":2},
	{ "name":"c3","id":3}
]
    原文作者:anne都
    原文地址: https://blog.csdn.net/qq_36958916/article/details/125636531
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞