Combining arrays of objects and converting them into a JSON array using Javascript

I struggle to seamlessly merge all the necessary transformations. I would greatly appreciate some assistance from those who are more comfortable with data manipulation, thank you.

Here is a visual representation of my objective:

[
    [
        {
            name : 'a',
            value : 'b'
        },
        {
            name : 'c',
            value : 'd'
        },
        ...
    ],
    [
        {
            name : 'e',
            value : 'f'
        },
        {
            name : 'g',
            value : 'h'
        },
        ...
    ],
    ...
]

// to

[
    {
        a : 'b',
        c : 'd'
    },
    {
        e : 'f',
        g : 'h'
    },
    ...
]

Answer №1

To see a live demonstration, visit this working fiddle: http://jsfiddle.net/x0PzG/

Below is the code snippet:

var data = [
    [
        {
            name : 'x',
            value : 'y'
        },
        {
            name : 'm',
            value : 'n'
        },
    ],
    [
        {
            name : 's',
            value : 't'
        },
        {
            name : 'u',
            value : 'v'
        },
    ],
]

function translateObjects(items) {
    var dictionary = {},
    object,
    index;
    for (index = 0; index < items.length; index++) {
        object = items[index];
        dictionary[object.name] = object.value;
    }
    return dictionary;
}

var translatedData = data.map(translateObjects);
alert(JSON.stringify(translatedData));

Answer №2

Take a look at the code snippet below. Hopefully this will assist you!

var data = [
    [
        {
            type : 'x',
            info : 'y'
        },
        {
            type : 'z',
            info : 'w'
        },
    ],
    [
        {
            type : 'm',
            info : 'n'
        },
        {
            type : 'o',
            info : 'p'
        },
    ]
];

var modifiedData = [];        
if(data.length){
    for(var i=0; i<data.length; i++){
        if(data[i].length){
            for(var j=0; j<data[i].length; j++){
                modifiedData.push("{"+data[i][j].type+":"+data[i][j].info+"}")
            }
        }
    }
}

console.log(modifiedData);

JSFiddle: http://jsfiddle.net/mail2asik/f7euL/

Answer №3

To simplify the code, you can utilize the reduce function:

var info = [
 [
    {
        name : 'a',
        value : 'b'
    },
    {
        name : 'c',
        value : 'd'
    },
 ],
 [
    {
        name : 'e',
        value : 'f'
    },
    {
        name : 'g',
        value : 'h'
    }
 ]
];

info = info.reduce(function(x, y, z){
    x[z] = y.reduce(function(q, r){
        q[r.name] = r.value;
        return q;
    }, {});
    return x;
}, []);

Check out the JSFiddle here

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

ReactJS Issue: Failure of Validation on Auto-Populated Form Field

I encountered an issue with the validation setup in my form. The validation checks the input values for "required", "max length", and "min length". Oddly, the validation only works for fields where the user manually types into the input field. I made some ...

What is the best way to reveal the following div while concealing the one before it?

Just starting out with Javascript, I'm currently developing a quiz solution that utilizes divs and buttons to navigate through the questions. I've written some JavaScript code for this functionality but I'm encountering an issue where it doe ...

What steps can I take to resolve the Angular JS error message: [$injector:unpr]?

index.html <!DOCTYPE html> <html lang="en" ng-app="myApp"> <head> <meta charset="UTF-8"> <title>Angular JS</title> <script src="lib/angular.min.js"></script> ...

Issue with Hover Effect on Safari Browser

Encountering a peculiar issue exclusively in Safari - when hovering over a link in the header, the links to the right of the hovered-over link alter their size (appearing smaller) during the hover animation. Once the animation concludes, these links revert ...

What differences exist in the implications of the options for the socket.io server object?

According to the socket.io documentation, you have the option to utilize the http.Server object or directly input a port number into the socket.io server object. What distinguishes the two methods? Instantiate the socket.io Object const io = require(&apo ...

Issue with Jest: Mocked function not found by Vue Component

I am currently in the process of mocking an ES6 class that is being utilized within my Vue Component: export default class DataUploadApi { // Get uploaded files static async getUploadedFiles() : Promise<Object> { return WebapiBase.ge ...

Exploring recursive looping within a directory using Emscripten's File API

Is there a way to iterate through files in a folder using Emscripten? For example, I have created a folder called '/res' (FS.mkdir('/res')) and added some temporary files and subfolders inside it. How can I go about looping through th ...

Use VueJS v-on:click and Vanilla JS to collapse various divs when clicked

Can VueJS and vanilla JS be used to collapse specific divs among many? I have information contained in separate card elements that include a title and a body. My goal is to make the body of each card expand or collapse when the respective title is clicked ...

Exploring the TLS configuration for a Node.js FTP server project: ftp-srv package

I'm seeking to comprehend the accurate setup of TLS for my FTP project (typescript, nodejs) using this API: ftp-srv The documentation provided is quite basic. In one of the related github issues of the project, the author references his source code / ...

The initial page load is experiencing issues with input type validations not functioning properly

I'm facing an issue with my text box where I only want to allow alphabets to be entered. Here is my code snippet: state ={ NomName: '', } onlyAlpha(e) { var regex = /^[a-zA-Z ]*$/; if(e.target.value === '' || regex.t ...

Unable to access a specific URL for the chosen items

I am looking to navigate to specific links when clicking on particular planets using raycaster. However, the current issue is that I get redirected to the URL of the last planet (referred to as category) whenever I click anywhere on the canvas. I have sepa ...

Can you determine the top-rated product category by comparing the arrays provided in JavaScript?

Here are two arrays to consider: const items = [ { name: 'item1', type: 'Fruit' }, { name: 'item2', type: 'Vegetable' }, { name: 'item3', type: 'Snack' }]; co ...

The discrepancy between the values returned from the 'slide' event upon release and the 'change' event in jQuery UI Slider

I'm currently working with a jQuery UI slider: $('div.slider').slider({ range: true, step: 250, min: 1000, max: 500000, values: [1000,500000], change: function(event, ui){ console.log($(this).slider('val ...

Exploring the Prototype-based programming concept in JavaScript

I am determined to deepen my understanding of JavaScript and explore what lies beneath its surface. While I have delved into various guides on the Object-Oriented Paradigm with Prototypes in JavaScript, I am struggling to comprehend how this paradigm diffe ...

Simplified syntax for conditionals or in comparison to multiple strings

This is what I currently have: if(this.selectedItem.label == "str1" || this.selectedItem.label == "str2" || this.selectedItem.label == "str3" || this.selectedItem.label == "str4") { } I am curious if there is a more concise way to refer to "this ...

Refreshing the Angular directive following a change in the scope variable

Just getting started with Angular and I've encountered a small issue. Within my template for SirroccoListing, I have the following code. Sirrocco is a directive: <h3>All Sirroccos</h3> <div sirrocco ng-repeat="sirrocco in sirroccos" ...

Challenges arise when attempting to iterate through nested arrays using a foreach loop

Having an issue with nested arrays in PHP while using foreach. I have a specific query that I need help visualizing: select systems.hostname, capacity_disk.server_id, capacity_disk.disk_mountpoint, capacity_disk.disk_datetime, capacity_disk.disk_device, c ...

Implementing a filter on retrieved data from an API in a React application

I'm retrieving information from this Api After fetching the data, I need to check if the gender is Male in order to display a Male Icon. How can I perform this check on the Api data and return some HTML data like an img tag or something to show the i ...

Laravel is encountering an issue due to incompatible data types being used as operands:

I have a Laravel booking clinic system. After running my code, I encountered the following error message: "Unsupported operand types: string / int" Here is the snippet of code in question: <li><img class="icons" src="{{a ...

Is there a specific advantage to iterating through arrays backwards in JavaScript?

Is it common practice in Javascript to use the following loop: for (var i = array.Length - 1; i >= 0; i--) { /* do something here */ }; I haven't seen this in other languages. Are there any advantages to this compared to: for (var i = 0; i < ...