javascript - 这个数据怎么整合?
阿神
阿神 2017-04-11 11:57:59
[JavaScript讨论组]

如何把list数组里每一个object的id键值对加到brandList数组的每一个object里?

阿神
阿神

闭关修行中......

全部回复(5)
PHP中文网

这样?

list.forEach(function(item, index){
    item.brandList.forEach(function(brandItem, brandIndex){
        brandItem.id = item.id;
    });
});
PHPz

如果你是要改变每一个的 id 属性,直接用 map 就好了:

var a = {
    brandList: [
        {
            brandName: 'a',
            id: 185,
            path: 'http://a.com'
        },
        {
            brandName: 'b',
            id: 186,
            path: 'http://b.com'
        },
        {
            brandName: 'c',
            id: 187,
            path: 'http://c.com'
        },
        {
            brandName: 'd',
            id: 188,
            path: 'http://d.com'
        }
    ],
    categoryName: '电子大亨',
    createDate: '2017-01-13 14:09:51',
    id: 9
}
var newA = a.brandList.map(function (e) {
    e.id = a.id;
    return e
});

输出结果:

阿神
list.forEach(listItem => {
    listItem.brandList.forEach(brandListItem => {
        brandListItem.id = listItem.id
    })
})
怪我咯

两个循环就好了 第一个循环拿到id 第二个循环把id添加进去,基本的数据操作嘛

天蓬老师

你真是比我都懒那

for(var i = 0;i<list.length;i++){
  var brandList = list[i]['brandList']
  for(var j = 0;j<brandList.length;j++){
    brandList[j]['id'] = list[i]['id']
  }
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号