js怎么改变嵌套数组里的值
大致的结构是这样
let arr = [{
id:0,
title:'A',
list:[
{pic:'../a.png',txt:'aaaa'},
{pic:'../b.png',txt:'bbbbbbb'},
{pic:'../c.png',txt:'cc'},
]
},
{
id:1,
title:'B',
list:[
{pic:'../a1.png',txt:'erse'},
{pic:'../b1.png',txt:'dfsdf'},
{pic:'../c1.png',txt:'gjgh'},
]
},
......
]
需要这样的
[
{id:0,
title:'A',
list:[
{name:'../a.png',txt:'aaaa',url:'../a.png'},
{name:'../b.png',txt:'bbbbbbb',url:'../b.png'},
{name:'../c.png',txt:'cc',url:'../c.png'},
]
},
{
id:1,
title:'B',
list:[
{name:'../a1.png',txt:'erse',url:'.../a1.png'},
{name:'../b1.png',txt:'dfsdf',url:'.../a1.png'},
{name:'../c1.png',txt:'gjgh',url:'.../a1.png'},
]
},
......
]
大致就是就是需要将数组中的list数组的json数据结构中的pic改造成自己想要的数据接口,例如:{name: arr中list的pci,....加入其它的自定义东西}
用 array的 map 方法,应该可以吧。
let arr = [{
id:0,
title:'A',
list:[
{pic:'../a.png',txt:'aaaa'},
{pic:'../b.png',txt:'bbbbbbb'},
{pic:'../c.png',txt:'cc'},
]
},
{
id:1,
title:'B',
list:[
{pic:'../a1.png',txt:'erse'},
{pic:'../b1.png',txt:'dfsdf'},
{pic:'../c1.png',txt:'gjgh'},
]
},
......
]
用map可以的
const newArr = arr.map(item => {item.list.forEach(list => {
list.url = '****.png'
})
return item
})
console.log(newArr)
`//直接改变原数组
arr.forEach(i => i.list.forEach((a, index, arr) => arr[index] = {name: a.pic,
url: a.pic,
txt: a.txt
}))
//不改变原数组
const newArr = arr.map(i => ({
...i,
list: i.list.map(a => ({
name: a.pic,
url: a.pic,
txt: a.txt
}))
}))`
回答
以上是 js怎么改变嵌套数组里的值 的全部内容, 来源链接: utcz.com/a/112360.html