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

Monitoring Javascript inactivity timeouts

As I work to incorporate an inactivity timeout monitor on my page, the goal is to track whether individuals working from home are present at their desks or not. The Jquery plugin http://plugins.jquery.com/project/timeout that I am utilizing initiates a ti ...

What is the method to disable response validation for image endpoints in Swagger API?

I'm working with a Swagger YAML function that looks like this: /acitem/image: x-swagger-router-controller: image_send get: description: Returns 'image' to the caller operationId: imageSend parameters: ...

Implementing a function trigger on button click using jQuery

I recently created a jQuery code snippet: <span id="counter-up" class="timer"> </span> <div class="buttons"> <button id="trigger">Find out!</button> </div> </div> <div class="container"> </div> & ...

Attempting to iterate through the div in order to collect all of the checkboxes and assign a label to each one

I am attempting to modify a piece of JavaScript code in order to locate all checkboxes, assign names to them, and then add label attributes with CSS for accessibility purposes. Here is the snippet of my existing code: <tr class="el-table__row" ...

Issue with iOS iframe scrolling - unable to scroll as expected

On iOS devices like the iPad and iPhone 6, scrolling doesn't seem to work as intended. Instead of the iframe scrolling, it's the 'body' that is moving. Javascript $(document).on(clickHandler, '#content a', function(){ href ...

Unable to clear cache in Next.js using RTK query

Currently, I am utilizing Next.js along with next-redux-wrapper and RTK Query. My application is performing external API requests on the server side. The implementation of the request looks like this: CompaniesPage.getInitialProps = initialPagePropsWithCom ...

What is the best method for converting Unix time to a readable date

<el-table-column label="Time Created" prop="create_time"></el-table-column> https://i.stack.imgur.com/aoLjf.png The timestamp data from the backend is in milliseconds format (e.g. 1527150668419) and is stored as create_time property in this.i ...

At the beginning of the application, access the Ionic Secure Storage using the get() method

I am facing an issue with retrieving a token for validating an Auth status in the /src/main.ts file: if (TokenService.getAccessToken() !== undefined) { ... } Here is my token.service.ts file: import storage from '@/plugins/storage' const ACCESS ...

Utilizing transitions to control the visibility of div elements

This is what I have achieved so far: function getOffsetRect(elem) { var box = elem.getBoundingClientRect() var body = document.body var docElem = document.documentElement var scrollTop = window.pageYOffset || docElem.scrollTop || body.sc ...

The issue of Ng-Route not functioning properly on a Node/Express static server

I need assistance with my app.js file that currently directs all requests to pages/index.html. Now I am attempting to utilize Angular to route user requests for '/#/media' by adding the following code: academy.config(function($routeProvider) { ...

The issue I am facing is with the post_logout_redirect_uri not functioning properly when using localStorage in an OIDC Auth

authority: 'yyy', client_id: this.'yyy', redirect_uri: 'http://localhost:4200/login', response_type: 'token', scope: 'yyy', post_logout_redirect_uri: & ...

Best practices for managing an array of buttons and handling click events in ReactJs

While working on my react class component, I encountered an issue. The alert popup keeps appearing constantly without any button click as soon as the component renders. onHandleOnClick(data, e) { console.log(data); alert("got it" + data); } rend ...

Using `window.location.href` will terminate any pending asynchronous calls to the API

Before all async calls to the API are completed, window.location.href is triggered when the code runs. Setting a breakpoint on the location resolves the issue. How can I ensure that all calls are finished before invoking window.location.href? Code: const ...

Top method for combining several external JavaScript libraries into a single one using webpack

Recently, I was diving into the world of webpack tutorial and it struck me that in order to combine everything into one module, scripts need to use require('./xyz'). Until now, I've always written individual scripts and loaded them in HTML u ...

Uh-oh, the Next.js fetch didn't go as planned. The error message

Currently, I am using Next.js 14 for my project. Suddenly, there has been an issue where some images are not loading on my local setup. However, the images load fine on the preview and production branches on Vercel. Upon checking my console, I noticed th ...

Is there a way to incorporate external HTML files into my webpage?

Looking to update an existing project that currently uses iFrames for loading external HTML files, which in this case are actually part of the same project and not from external sites. However, I've heard that using iFrames for this purpose is general ...

What steps should be taken to fix the sinopia installation error?

While operating on redhat5.9, I encountered an exception related to 'make'. I am curious about what they are trying to create. It seems like it's related to JavaScript. [root@xxxx bin]# npm install -g sinopia --python=/usr/local/clo/ven/pyt ...

ES modules' `require()` functionality is not supported

Issue: Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: D:\...\node_modules\normalize-url\index.js [0] require() of ES modules is not supported. [0] require() of D:\...\node_modules\normalize-url\index.js ...

What is the best way to implement ng-model in conjunction with ng-repeat?

I created a form using ng-repeat, but I am struggling to incorporate ng-model into it. I attempted to use track by $index without success. While I found examples of using ng-model with values in an object, that's not what I'm looking for. I simp ...

The connection to the firebase callback

Upon examining this function, it appears that there may be an issue with a null value causing the error message to display: (node:16232) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'groupPages' of null async setTriggers() { ...