如何将数组合并到json以形成预期结果

时间:2016-06-08 14:00:18

标签: javascript arrays json node.js express

我有一个JSON数组:

var row={ shopId: 3, shopName: '1', address: 'abc', contactNumber: 1234 }

我有一个数组:

var data= [ { imageId: 1, shopId: 3, imageUrl: 'aaa' },
            { imageId: 2, shopId: 3, imageUrl: 'bbb' } ]

我必须合并这两个并输出如下:

var result = {
    shopId: 3,
    shopName: '1',
    address: 'abc',
    contactNumber: 1234,
    image: [{
        imageId: 1,
        shopId: 3,
        imageUrl: 'aaa'
    }, {
        imageId: 2,
        shopId: 3,
        imageUrl: 'bbb'
    }]
}

4 个答案:

答案 0 :(得分:1)

您可以撰写row['image'] = data;row.image = data;

答案 1 :(得分:1)

只需将data分配给row.image,就像这样:



var row = {
  shopId: 3,
  shopName: '1',
  address: 'abc',
  contactNumber: 1234
}

var data = [{
  imageId: 1,
  shopId: 3,
  imageUrl: 'aaa'
}, {
  imageId: 2,
  shopId: 3,
  imageUrl: 'bbb'
}]

var result = row.image = data;

console.log(row)




答案 2 :(得分:1)

如果数据包含{3}以外的filter的对象,则可以使用shopId



    var row={ shopId: 3, shopName: '1', address: 'abc', contactNumber: 1234 }

    var data= [ { imageId: 1, shopId: 3, imageUrl: 'aaa' },
                { imageId: 2, shopId: 3, imageUrl: 'bbb' },
                { imageId: 2, shopId: 5, imageUrl: 'bbb' }];

row.images = data.filter( el => el.shopId == row.shopId);

console.log(row);




答案 3 :(得分:1)

如果您不想修改原件,也可以使用



var  row = { shopId: 3, shopName: '1', address: 'abc', contactNumber: 1234 },
    data = [ { imageId: 1, shopId: 3, imageUrl: 'aaa' }, { imageId: 2, shopId: 3, imageUrl: 'bbb' } ],
   combo = Object.assign({},row,{["image"]:data});
console.log(combo);