Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.3k views
in Technique[技术] by (71.8m points)

js 往数组中遍历三个元素

例如

let arr = [
    {id:0,title:'T1'},
    {id:1,title:'T2'},
    {id:2,title:'T3'},
    {id:3,title:'T4'},
    {id:4,title:'T5'}
    ...
]


let img = [
 {id:0,pic:'/01.png'},
 {id:1,pic:'/02.png'},
 {id:2,pic:'/03.png'}
 ...
]

将 img数组的图片往arr数组对象中循环插入,类似于这样

let arr = [
    {id:0,title:'T1',img:'/01.png'},
    {id:1,title:'T2',img:'/02.png'},
    {id:2,title:'T3',img:'/03.png'},
    {id:3,title:'T4',img:'/01.png'},
    {id:4,title:'T5',img:'/02.png'}
    ...
]

怎么操作??


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

你这个需求,根据相同的键(id)合并两个对象,适合直接用Object.assign()这个内置方法,具体用法可以看这里https://developer.mozilla.org...

  let arr = [
        {id:0,title:'T1'},
        {id:1,title:'T2'},
        {id:2,title:'T3'},
        {id:3,title:'T4'},
        {id:4,title:'T5'}
    ]
    let img = [
        {id:0,pic:'/01.png'},
        {id:1,pic:'/02.png'},
        {id:3,pic:'/03.png'},
        {id:4,pic:'/03.png'},
        {id:5,pic:'/03.png'}
    ]
    for(let i=0; i<arr.length; i++) {
        Object.assign(arr[i],img[i])
    }
    console.log(arr);

输出结果:
image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...