我正在使用 Amazon Web 服务及其数据库 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]
如果您还想保留 Items key ,请使用:
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);
关于javascript - 将 JSON 数组的一部分与另一个 JSON 数组组合起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33910617/