Combine similar JSON objects into arrays

I'm working with a dataset returned by a library, and it's structured like this:

var givenData = [{"fName": "john"}, {"fName": "mike"}, {"country": "USA"}]

My goal is to group the "fName" values together and add '[]' to achieve the following result:

{ 'fName[]': ['john','mike'],'country[]': ['USA'] };

Keep in mind that country and fName are completely unrelated.

Answer №1

Recommendation (utilizing ES6 syntax)

const restructureData = (data) => {
  const modifiedData = {}
  data.forEach( (item) => {
    for (let property in item) {
       const newProperty = property + "[]"
       if (!modifiedData.hasOwnProperty(newProperty)) modifiedData[newProperty] = []
       modifiedData[newProperty].push(item[property])
    }
  })
  return modifiedData
}

/* added some additional properties to test */
let providedData = [
  {"name": "Alice", "age": 25}, 
  {"name": "Bob"}, 
  {"age": 30},
  {"gender": "Female"}
]

console.log(restructureData(providedData))
/*
{
    "name[]": ["Alice","Bob"],
    "age[]": [25,30],
    "gender[]":["Female"]
}
*/

Answer №2

To add the date to a specific field, you can loop through the array and insert it accordingly.

var givenData = [{"fName": "john"}, {"fName": "mike"}, {"country": "USA"}]

var result = {
  'fName[]': [],
  'country[]': []
};

givenData.forEach(function (data) {
  if (data.fName) {
    result['fName[]'].push(data.fName);
  }
  
  if (data.country) {
    result['country[]'].push(data.country);
  }
});

console.log(result);

Answer №3

To create an organized data structure, you can extract the key and use it to build an object with arrays as its properties.

var inputArray = [{"name": "Alice"}, {"name": "Bob"}, {"country": "Canada"}],
    organizedData = inputArray.reduce(function (result, obj) {
        var key = Object.keys(obj)[0] + '[]';
        result[key] = result[key] || [];
        result[key].push(obj[Object.keys(obj)[0]]);
        return result;
    }, Object.create(null));

console.log(organizedData);

Answer №4

When using ES6 syntax:

const updatedData = givenData.reduce((result, obj) => {
   const key = `${Object.keys(obj)[0]}[]`;
   return { ...result, [key]: [ ...result[key], obj[key] ] }
 }, {});

This approach preserves the original data and provides a neat solution.

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

Determine the difference between the starting and ending dates in AngularJS

In my project, I am trying to implement a feature where an error message should be displayed next to the control if the "ToDate" is before the "FromDate". Currently, I have set a minimum date which successfully disables the selection of ToDate before FromD ...

Troubles with data retrieval in AngularJS when attempting to send data via post request

When I receive an ID from the URL, I pass it to a PHP server page. In AngularJS, this is how I extract the ID from the URL and send it using the post method: (NOTE : When I retrieve data and print it with console.log(), everything seems fine. The issue ...

Child component in Angular2 makes an observer call to its parent object

Let me try to explain this in the best way possible. I have a service that includes an observable class responsible for updating itself. This observable class needs to be pushed out to the app using the observer within the service. How can I trigger that ...

Building paths through a jQuery loop

Transform String into Delimited Array, Generate Loop of Check Boxes, and Build New String Given String = "Folder Tier1\Folder Tier2\Folder Tier3\Folder Tier4\Folder Tier5\Folder Tier6\" (Missing) Use "\" as a delimi ...

The price filter slider is experiencing issues with the onresize function not functioning properly

I am facing an issue with a price filter I developed for my project. Despite having coded it, the filter is not functioning properly. <div class="price_range_caption"> <span class="currency_from">Rs.</span><span id="price_range_f ...

What is the best way to assign a unique number to every div id that is generated?

I am currently using a django for loop to retrieve data from a query set. As the information is displayed, I would like to have each item wrapped in a div tag with a unique id that increments by 1 for every instance. Is there a way to achieve this directly ...

An error occurred as the Serverless Function timed out while attempting to load a dynamic route in Next.js version 13

I have a basic Next.js application with the following route structure: /contentA/ - Static - Initial load: 103 kB /contentA/[paramA]/groups - SSG - Initial load: 120 kB /contentB/[paramA]/[paramB]/[paramC] - SSR (client component) - Initial load: 103 kB ...

Switch the orientation of a live table moving horizontally to vertically and vice versa

config.previewData = [ { Products:27989, Total Customers:294, Metrics:"MVC", Toner Products:5928, INK Products:22061 }, { Products:56511, Total Customers:376, Metrics:"SMB", ...

How to utilize View as a substitute for the div tag in your Web Project

Undoubtedly, when working on a web project, it is common practice to use the div element like this: <div> sample text </div> However, using div in React Native can lead to errors: <View> sample text </View> Is there a way to ...

Organizing an array of objects by sorting them according to their internal data and grouping them together

Looking to organize this array of objects in a hierarchical structure: var channels = [{ cid: 5, pid: 10 }, { cid: 10, pid: 0 }, { cid: 20, pid: 5 }, { cid: 15, pid: 10 }]; In this case, cid represents channel Id and pid r ...

React component rendering twice due to width awareness

In a React component that I've developed, I have utilized ResizeObserver to track its own width. Within this component, two divs are rendered with each having a "flex: 1" property to ensure equal width distribution. Under certain conditions, such as w ...

Comparing two datetime objects with time zone offsets in JavaScript: How to determine if one is greater than or less than the other?

So I'm faced with a situation where I need to compare two dates where the first date is 05.01.2008 6:00 +5:00 and the second date is 05.01.2008 7:00 +5:00 I'm struggling to find a way to convert these datetimeoffsets into a specific forma ...

Transfer information via query or retrieve from storage in Vue

When considering sending a data variable to another component, is it more efficient to send it via query using a router or save the data in-store? Which method would be more optimal? router.replace({ name: 'routerName', query: { param ...

What is the best way to refresh a Windows 7 command prompt screen before executing a new function in Node.js?

I attempted system calls for cls and also tested out this code snippet: function clear() { process.stdout.write('\u001B[2J\u001B[0;0f'); } Unfortunately, none of the options seem to be effective. ...

What are the benefits of declaring variables with JSON in a JavaScript file instead of simply reading JSON data?

Lately, I've been delving into the world of leaflets and exploring various plugins. Some of the plugins I've come across (like Leaflet.markercluster) utilize JSON to map out points. However, instead of directly using the JSON stream or a JSON fi ...

Steps to partially open the Modal Sheet Swipe Step by default

I've set up a modal sheet component with the following structure: <f7-sheet class="myClass" style="height: auto" swipe-to-step :backdrop="false" > <div class="sheet- ...

Retrieving information from MongoDB

Currently, I am working on retrieving data from MongoDB and passing it to my Express server to eventually display it in my HTML using Angular. The retrieval process is successful when there is only one record in the database. However, if multiple records a ...

Can applications on Windows 8 operate using JavaScript, HTML5, and CSS3 that adhere to industry standards?

As a .NET developer, I tuned in to the keynote for the Build Event in Anaheim, California and had some questions regarding the new support for creating Windows 8 applications using JavaScript, HTML5, and CSS3. They showcased several examples and mentioned ...

Can someone please help me figure out why the "setInterval" function in my script isn't functioning as expected?

I've been experimenting with controlling the refresh rate of drawn objects in a canvas using JavaScript. Even after going through the tutorials and examples on w3.school, I'm still unsure why the "setInterval" function is not executing the "gener ...

Triggering a function in response to a click

I'm encountering an issue with calling a callback inside a click event. Initially, I am attaching the click event to each table row. jQuery(tr).click(function (event) { var that = this; A(event, that, function () { var $gantt_containe ...