将JSON数组的一部分与另一个JSON数组组合在一起

combines parts of a JSON array with another JSON array

本文关键字:JSON 数组 组合 在一起 另一个 一部分      更新时间:2023-09-26

我使用的是亚马逊网络服务和他们的数据库dynamodb。数据库以json的形式返回一个查询,例如:

{ Items: 
   [ { user: 'a' },
     { user: 'an' },
     { user: 'm' } ],
  Count: 3,
  ScannedCount: 3 }

我只对"用户"属性感兴趣,对计数和扫描计数没有任何用处。有时我会在应用程序服务器(nodejs)中执行多个请求并接收多个json响应。我想把所有这些响应组合成一个json。从本质上讲,将所有用户的组合到一个json数组中并将其发回。所以有时我可以收到这样的请求:

{ Items: 
   [ { from_username: 'a' },
     { from_username: 'an' },
     { from_username: 'm' } ],
  Count: 3,
  ScannedCount: 3 }

{ Items: 
   [ { from_username: 'a' } ],
  Count: 1,
  ScannedCount: 1 }

{ Items: 
   [ { from_username: 'v' },
     { from_username: 'a' }],
  Count: 2,
  ScannedCount: 2 }

我想把它合并成这样的东西:

   {Items:
   [ { from_username: 'a' },
     { from_username: 'an' },
     { from_username: 'm' },
     { from_username: 'a' },
     { from_username: 'v' },
     { from_username: 'a' } ]

我试过这样的东西:

var json = [json1, json2, json3]

但这只是凹入,并没有删除不需要的计数字段。

不要在数组中复制整个json,只将json的Items属性添加到数组中

var json = [json1.Items, json2.Items, json3.Items]

如果你想保留项目密钥,也可以使用:

var json = [{Items: json1.Items}, {Items: json2.Items}, {Items:json3.Items}]

如果你想把所有项目都放在一个数组下,你可以使用:

var json = {Items: []};
json.Items = json.Items.concat(json1.Items);
json.Items = json.Items.concat(json2.Items);
json.Items = json.Items.concat(json3.Items);