test test - 29 days ago 7
Javascript Question

Push/Assign JSON child string to respective parent

I have a JSON string which is generated from an API.

[{"categories":{"category":{"id":"1","Name":"furit"}}},{"categories":{"category":{"id":"2","Name":"veg"}}},{"products":{"product":{"id":"1","Name":"fruit"}}},{"products":{"product":{"id":"2","Name":"pears"}}}]


how can I push all child values to their parent to look something like this.

[{"categories":{"category":[{"id":"1","name":"fruit"},{"id":"2","name":"veg"}]}},{"products":{"products":[{"id":"1","name":"apple"},{"id":"2","name":"pears"}]}}]


Thanks.

Updated data structure


Answer Source

You can create new object and use map to change your data structure and assign that data to new object.

var data = [{"categories":{"category":{"id":"1","Name":"furit"}}},{"categories":{"category":{"id":"2","Name":"veg"}}}]
  
var r = {
  categories: {
    category: data.map(o => o.categories.category)
  }
}
console.log(r)

Updated For new data structure you can use forEach() loop and add to object.

var data = [{"categories":{"category":{"id":"1","Name":"furit"}}},{"categories":{"category":{"id":"2","Name":"veg"}}},{"products":{"product":{"id":"1","Name":"fruit"}}},{"products":{"product":{"id":"2","Name":"pears"}}}]

var r = {categories: {category: []}, products: {product: []}}
data.forEach(function(e) {
  if(e.categories) r.categories.category.push(e.categories.category)
  if(e.products) r.products.product.push(e.products.product)
})

console.log(r)