James James - 2 months ago 7
Javascript Question

Adding to Javascript Object Without Replacing Child

I am trying to run a for loop to create new javascript objects and add to an existing javascript object without replacing.

For example I am trying to create this as the output without the group[i] being overwritten every time ( and just adding the number[i] data ):

{
"group1": {
"number1": "data",
"number2": "data",
"number3": "data"
},
"group2": {
"number1": "data",
"number2": "data"
}
}


My loop looks like this:

var array = [{
"groupName": "group1",
"number": "number1",
"data": "data"
}, {
"groupName": "group1",
"number": "number2",
"data": "data"
}, {
"groupName": "group1",
"number": "number3",
"data": "data"
}, {
"groupName": "group2",
"number": "number1",
"data": "data"
}, {
"groupName": "group2",
"number": "number2",
"data": "data"
}]

var groupLinks = {};

for(i = 0; i < array.length; i++) {

groupLinks[array[i].groupName] = {
[array[i].number]: array[i].data

}


As you can see with this code, my loop is only going to replace "group1" and "group2" every time.

Answer

This is how I would go about approaching this:

var array = [{
    "groupName": "group1",
    "number": "number1",
    "data": "data"
}, {
    "groupName": "group1",
    "number": "number2",
    "data": "data"
}, {
    "groupName": "group1",
    "number": "number3",
    "data": "data"
}, {
    "groupName": "group2",
    "number": "number1",
    "data": "data"
}, {
    "groupName": "group2",
    "number": "number2",
    "data": "data"
}];

var groupLinks = {};

array.forEach(
    function (element)
    {
        var groupName = element.groupName;
        (groupLinks[groupName] = groupLinks[groupName] || {})
            [element.number] = element.data;

    }
);

console.log(groupLinks);

here I used the || operator to create a new group when none was present, overwriting the existing groupLinks[groupName] at each iteration, and I used a forEach construct to loop over array elements.

Comments