Transform JSON from an array of objects to objects of arrays

I have a dataset of JSON entries:

[{"num": "1","name_A": "Alex" ,"name_B": "Bob"}, {"num": "2","name_A": "Anne" ,"name_B": "Barbra"}]

My goal is to effortlessly convert this collection of Objects into two separate objects - one labeled name_A, and the other as name_B. Each object should consist of the label and an array of corresponding num-name pairs:

[{title: "name_A", names:[{"1", "Alex}, {"2", "Anne"}]}, {title:"name_B", names: [{"1", "Bob"}, {"2", "Barbra"}]}]

Initially, I attempted to create the two objects by using array reduction twice, first for name_A and then for name_B before merging them together:

// obtain 'names' array
var name_A = objArray.reduce(function(memo, curr) {
    memo.push({curr.num, curr.name_A})
    return memo;
}, []);

However, my approach seems to be failing. Why is there no push method for memo when initializing reduce with an empty array?

Furthermore, am I steering in the right direction or is there a more efficient way to accomplish this task?

Answer №1

Some minor corrections have been made to the expectations in the comments below.

var input = [{ "num": "1", "name_A": "Alex", "name_B": "Bob" }, { "num": "2", "name_A": "Anne", "name_B": "Barbra" }]

var output = input.reduce(function (a, b) {
    // Construct new objects and assign their properties
    var i = {};
    i[b.num] = b.name_A;
    var j = {};
    j[b.num] = b.name_B;

    // Add them to our collection elements
    a[0].names.push(i);
    a[1].names.push(j);

    return a;
   // Initialize our collection
}, [{ title: "name_A", names: [] }, { title: "name_B", names: [] }]);

// Print the output in a readable format
console.log(JSON.stringify(output, null, "     "))

var input = [{ "num": "1", "name_A": "Alex", "name_B": "Bob" }, { "num": "2", "name_A": "Anne", "name_B": "Barbra" }]

var output = input.reduce(function (a, b) {
  // Construct new objects and assign their properties
  var i = {};
  i[b.num] = b.name_A;
  var j = {};
  j[b.num] = b.name_B;

  // Add them to our collection elements
  a[0].names.push(i);
  a[1].names.push(j);

  return a;
  // Initializing our collection
}, [{ title: "name_A", names: [] }, { title: "name_B", names: [] }]);

so.log(output)
<pre id="output"></pre>
<script>
  var so = {
    log: function(o) {
      document.getElementById("output").innerHTML = JSON.stringify(o, null, "     ")
    }
  }
</script>

Answer №2

Your code is encountering an issue because the object { curr.num, curr.name_A } lacks property names. To address this, I have included properties num and name in the revised code below.

var nameListA = [];
var nameListB = [];
objArray.forEach(function(curr) {
    nameListA.push({num: curr.num, name: curr.name_a});
    nameListB.push({num: curr.num, name: curr.name_B});
});
var modifiedResult = [ 
    { title: "name_A", names: nameListA },
    { title: "name_B", names: nameListB }
];

In addition, for creating an array from iterating over another array, it is recommended to utilize .map instead of .reduce.

Answer №3

Assuming that only the property num remains constant, all other properties are considered as data, such as name_A or name_B.

let items = [{ "num": "1", "name_A": "Alice", "name_B": "Ben" }, { "num": "2", "name_A": "Anna", "name_B": "Brian" }],
    finalResult = [];
items.forEach(function (element) {
    let number = element.num;
    Object.keys(element).forEach(function (key) {
        function findIndexAndAssignNames(arr, ind) {
            if (arr.title === key) {
                finalResult[ind].names[number] = element[key];
                return true;
            }
        }

        if (key !== 'num' && !finalResult.some(findIndexAndAssignNames)) {
            let newItem = {};
            newItem[number] = element[key];
            finalResult.push({ title: key, names: newItem });
        }
    });
});
document.write('<pre>' + JSON.stringify(finalResult, 0, 4) + '</pre>');

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

"Receiving an error message on Windows while trying to execute a package in Node.js: 'Cannot access property 'toString' of null

Utilizing the gulp and hercule packages on node.js to transclude some plain text files has been smooth sailing on Unix. However, encountering hiccups when running it on Windows. Colleagues are facing a specific error message while working on Windows: [13: ...

What is the best way to utilize :focus while simultaneously applying properties through Javascript?

When styling an input element with JavaScript, it seems that any properties set this way are ignored in a :focus rule. An example is provided to illustrate this: Initially, the background and border of the input element matches the surrounding element ( ...

Here's a unique rewrite of the text: "What is the best way to run a JavaScript script in Java and

Currently in the process of automating a web application that utilizes SmartClient, I am in need of a reliable method for constructing locators for forms and populating input fields. Our testing framework is based on Selenium and SmartClient's scLocat ...

The THREE.EffectComposer function cannot be used as a constructor

Greetings fellow developers! Today, I embarked on a journey to create a volumetric light scattering shader using THREE.js. My inspiration came from this amazing example: https://codepen.io/abberg/pen/pbWkjg However, as I attempted to implement the code, ...

What is the best way to access and compare the values within each <td> element?

, my code looks like this: <table id="table_append"> <tr class='text-center'>" + <td>1</td> <td class="codeverify">025</td> <td> Data1 </td> </tr> ...

What is the best way to implement horizontal content scrolling when an arrow is tapped in mobile view?

I recently created a JS Fiddle that seems to be working fine on desktop, but in mobile view, the square boxes have horizontal scrolling. Here are the CSS codes I used for this particular issue: @media only screen and (max-width: 767px) { .product-all-con ...

Error: When executing a NSDictionary query, an "unrecognized selector sent to instance" error is being returned

I am in the process of setting up a new function for my iOS application: - (IBAction)nextButton:(id)sender { if (self.itemSearch.text.length > 0) { [PFCloud callFunctionInBackground:@"eBayCategorySearch" withP ...

Is there a way to eliminate backslashes from a JSON string?

I'm dealing with a JSON string that appears like this: '{\"test\":{\"test1\":{\"test1\":[{\"test2\":\"1\",\"test3\": \"foo\",\"test4\":\"bar\",\"test5 ...

TWIG - when a variable matches an object attribute

Having just dipped my toes into Twig, Symfony2, and PHP, I find myself faced with a challenge. I have an array of objects where I can access attributes using {{result.attribute1}} after a {for result in results} loop. My goal is to utilize a variable {{va ...

Retrieve characteristics from removed or replicated entities and allocate them to different entities

Looking for a bit of assistance with an array transformation: [ {Code:13938, Country:699, Name:"Crocs", codeProduct:1} {Code:13952, Country:699, Name:"Polo Club", codeProduct:14} {Code:13952, Country:699, Name:"Polo Club", codeProduct:1} {Code ...

Allow undici fetch requests to use self-signed certificates

What is the correct way to execute fetch('https://localhost:8888') when dealing with a locally hosted HTTP server that uses a self-signed certificate (using fetch which is derived from undici)? ...

What is the purpose of using $ symbols within NodeJS?

Lately, I've been attempting to grasp the ins and outs of using/installing NodeJS. Unfortunately, I'm feeling a bit lost due to tutorials like the one found here and their utilization of the mysterious $ symbol. Take for instance where it suggest ...

Even though my performance in a sandbox environment is excellent, I am unable to obtain a token in a production environment

After posting my question on the Evernote developer forum, I was disappointed to find that the forum had been closed before I received a response. Even after receiving a proposal from an Evernote employee named chanatx to verify if my key was activated co ...

Incorporating an image as a clickable element instead of a traditional button using HTML and

Here's the issue at hand: I currently have "+" and "-" icons at the end of each row to add and delete rows as needed. However, I would like to replace the "-" icon with a trashcan symbol instead. I attempted to do this by replacing it with an image s ...

Attempting to alter an image with a click and then revert it back to its original state

I'm currently working on a feature that toggles an image when a specific class is clicked. The code I have so far successfully switches from 'plus.png' to 'minus.png' upon clicking, but I need it to switch back to 'plus.png&ap ...

Ways to ensure your Javascript code only runs based on the specific browser

I need a Javascript code to run depending on the browser version. Specifically, if the browser is not IE or is IE 9+, one piece of Javascript should be executed. If the browser is IE8 or lower, another piece of Javascript should be executed. My attempt to ...

What is the best way to send a multidimensional char array as a parameter in a C function?

I'm facing an issue with my code - it's not working properly. When I pass a char array like grid[r][c], I get the following errors: [Error] use of parameter 'r' outside function body [Error] use of parameter 'c' outside func ...

Transitioning in Vue.js can be triggered by changing a value up or down

My current transition block component is set up like this: <div v-if="!surveyResultIsReady" class="vh-md-40 position-relative" > <transition name="custom-classes-transition" enter-active-class="animated slideInRight" ...

Why is it that this code can upload photos successfully, but not text files?

This is my PHP file for handling form actions. I have successfully implemented image uploads, but I am encountering an 'Invalid File Error' when trying to upload text files. What could be causing this error and how can I resolve it? <?php e ...

Eliminating repeated entries in MongoDB

Hey guys, I've been struggling for days trying to eliminate all the duplicates from my database. I attempted a solution I came across on this Link, but encountered an error message stating that forEach is not a function. I'm puzzled as to why it ...