user2924127
user2924127

Reputation: 6252

combines parts of a JSON array with another JSON array

I am using Amazon web services and their database dynamodb. The database returns a query in the form of json such as this:

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

I am only interest in the "user" attributes and have no use for the count and scanned count. Sometimes I do multiple requests and recieve multipel json responses inside of my application server (nodejs). I would like to combine all these response into one json. Essentially combine all the user's into one json array and send it back. So somethimes I can reive requests such as this:

{ 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 }

And would like to combine it into something like this:

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

I tried something like this:

var json = [json1, json2, json3]

But this only concats and does not remove the unwanted count fields.

Upvotes: 0

Views: 143

Answers (1)

prasun
prasun

Reputation: 7343

Instead of copying entire json in the Array, add only Items attributes of JSON to the array

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

If you want to retain Items key as well use:

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

If You want all Items under one array Instead you can use:

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

Upvotes: 2

Related Questions