Associate JSON sub-string with corresponding main parent

I am working with a JSON string that is generated from an API.

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

I want to restructure the data so that all child values are pushed to their parent. Here is an example of how I would like the data to look:

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

Thank you in advance for your help.

Updated data structure

Answer №1

To transform your data structure, you can create a new object and use the map function. Then, assign the modified data to the 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)

For an updated data structure, utilize a forEach() loop to populate the object with the new data.

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)

Answer №2

You can utilize the Array.prototype.reduce() method to condense all the items in your array of category objects into a single categories array, resulting in the desired outcome.

Your code should appear as follows:

var result = data.reduce(function(a, b) {
  a[0].categories.push(b.categories);
  return a;
}, [{
  categories: []
}]);

Alternatively, if you prefer an object as the output instead of an array, you can use the following:

var result = data.reduce(function(a, b) {
  a.categories.push(b.categories);
  return a;
}, {
  categories: []
});

Example:

var data = [{
    "categories": {
      "category": {
        "id": "1",
        "Name": "fruit"
      }
    }
  },
  {
    "categories": {
      "category": {
        "id": "2",
        "Name": "veg"
      }
    }
  }
];

var result = data.reduce(function(a, b) {
  a[0].categories.push(b.categories);
  return a;
}, [{
  categories: []
}]);

console.log(result);

Update:

This update includes adding products to the original object:

var result = data.reduce(function(a, b) {
  if(b.categories)
      a[0].categories.push(b.categories);
   if(b.products)   
       a[0].products.push(b.products);
  return a;
}, [{
  categories: [],
  products : []
}]);

Example:

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

var result = data.reduce(function(a, b) {
  if(b.categories)
      a[0].categories.push(b.categories);
   if(b.products)   
       a[0].products.push(b.products);
  return a;
}, [{
  categories: [],
  products : []
}]);

console.log(result);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Migration of old AngularJS to TypeScript in require.js does not recognize import statements

I am looking to transition my aging AngularJS application from JavaScript to TypeScript. To load the necessary components, I am currently utilizing require.js. In order to maintain compatibility with scripts that do not use require.js, I have opted for usi ...

Extract the "_id" value from the array in the v-for loop and then store and reuse it in the data object // using vue-cli

Currently, I am iterating through [postArray] to retrieve various posts, each of which has its own unique "_id". My goal is to utilize this "_id" to add likes to the corresponding post. This is the v-for loop I am using: <div class="posts" v- ...

The expression req.files consistently comes back as an empty [object]

I have been encountering an issue with saving uploaded files using their original names (with express-fileupload). Whenever I upload a file, it gets saved in the directory as [object Object]. Node: var express = require('express') var app = exp ...

Ways to retrieve numerous data points from an array of dictionaries?

Just starting out with Python and in need of some guidance. I have a list of dictionaries sourced from a json file: x = [{'competition_id': 16, 'season_id': 4, 'country_name': 'Europe', 'competition_name': ...

I could really use some assistance with this project for my friend

Whenever I click on the image, it only displays two out of the three possible alerts. How can I make it show all three? Here's my code: <!DOCTYPE html> <html> <head> </head> <body> <img src="http://www.build ...

What is the jquery alternative to the PHP 'if IP equals' condition?

I am curious to know if the following PHP 'if' conditions can be achieved in jquery or JavaScript, with a preference for jquery. if ($_SERVER['REMOTE_ADDR'] != '123.99.55.616') { // public doingness } if ($ ...

Issue with child prop not being updated despite changes in parent component

I'm facing a strange issue where altering a child component's prop doesn't trigger a re-render. Here's the scenario: In the parent component, I have: <child :problemProp="proplemPropValue"></child> In the child component, ...

The customized uploading button functions seamlessly on desktop devices, yet encounters issues when used on

On my website, I have implemented a custom upload button alongside a hidden file input with the class .invisible-file-input. Here is how it is set up: Javascript $('.call-upload').click(function () { $(this).siblings('.invisible- ...

HTML code causing an Ajax post request to return a null value

How can I send JSON data from HTML to PHP using the Ajax post method? I have looked at various resources like this and this but so far, I am only getting a null return value. Other similar questions have not been helpful either. HTML (jQuery Ajax): $(&apo ...

Having issues with socket.io connectivity on my Node server

I am setting up my node server to update all connected clients with real-time information. However, when I run the code provided below, the io.sockets.on('connection') callback keeps firing constantly, flooding the console with the message Client ...

combination of Vue methods from a separate file

Having some trouble sharing a method in Vue across files. Despite trying various suggestions found through research, I haven't been able to make it work. I did manage to get mixins working within the same file, but couldn't figure out how to impo ...

What is the best Haskell library for handling JSON data?

With approximately twelve JSON packages available on Hackage for Haskell, how can I determine which one is the best fit for my needs? Is there a way to gauge popular opinion on these packages? Is there any data available regarding the usage and popularity ...

Can HTML text areas be designed to adjust their width automatically, as well as their height?

Among the numerous StackOverflow examples showcasing an auto-height Textarea, one noteworthy example can be found here: <textarea oninput="auto_grow(this)"></textarea> textarea { resize: none; overflow: hidden; min-heig ...

Utilizing a dynamically created Stripe checkout button

Currently, I am attempting to integrate a checkout button from the Stripe Dashboard into my VueJS Project. I have a feeling that I might not be approaching this in the correct manner, so if you have any advice, I would greatly appreciate it. In order to ...

"Learn how to use JavaScript and jQuery to alphabetically sort the default td values in a table

This table and script are being used to alphabetically sort the data within the td tags: <button type=button>Sort Options</button> <table class="table-data"> <tr> <td class="filename">C</td> </tr> <t ...

Struggling to retrieve the fake JavaScript data for my Vue.js table

I am a beginner in the development field and encountering the following error report while working with Vue.js 3 115:5 error 'vendorTable' is assigned a value but never used no-unused-vars 115:23 error 'Vue' is not defined no- ...

Troubleshooting a Multi-dimensional Array Reference Issue

Currently, I am working with an Array and need to modify the last item by pushing it back. Below is a simplified version of the code: var array = [ [ [0,1,2], [3,4,5] ] ]; //other stuff... var add = array[0].slice(); //creat ...

Easy steps for importing node modules in TypeScript

I'm currently navigating the world of TypeScript and attempting to incorporate a module that is imported from a node module. I have chosen not to utilize webpack or any other build tools in order to maintain simplicity and clarity. Here is the struct ...

Do JavaScript have dictionary functionality similar to Python?

I am trying to create a dictionary in JavaScript that looks something like this: I can't recall the exact syntax, but it was similar to: states_dictionary={ CT=[alex,harry], AK=[liza,alex], TX=[fred, harry] ........ } Does JavaScript support this ty ...

Encountering a duplicate key error in ExpressJS collection

Whenever I try to create a new event with categories that already exist in my database, such as creating an event with the category "javascript" and then attempting to create another event with categories "javascript, html, css", I encounter the error mess ...