N85
N85

Reputation: 63

Push nested object to array

how to push nested json object into array. This is sample json object. Assume I have 100 GROUP.

data="result": {
    "GROUP_A": {
        "statistics": {
            "year2000": 8666,
            "year2001": 1213,
            "year2002": 123,
        },
        "trending": {
            "year2000": 90,
            "year2001": 78,
            "year2002": 86,
        }
    }
    "GROUP_B": {
        "statistics": {
            "year2000": 43223,
            "year2001": 4234,
            "year2002": 124343,
        },
        "trending": {
            "year2000": 34,
            "year2001": 43,
            "year2002": 45,
        }
    }
}

Example output is below:

"result": [{
    "GROUP_A": [{
        "statistics": {
            "year2000": 8666,
            "year2001": 1213,
            "year2002": 123,
        },
        "trending": {
            "year2000": 90,
            "year2001": 78,
            "year2002": 86,
        }
    }]
    "GROUP_B": [{
        "statistics": {
            "year2000": 43223,
            "year2001": 4234,
            "year2002": 124343,
        },
        "trending": {
            "year2000": 34,
            "year2001": 43,
            "year2002": 45,
        }
    }]
}] 

I have no idea to do. If simple object I can push like this:

var arr=[];

arr.push(data);

Reason to push into array because the key object for group is dynamic. I want to use group for filtering data.

Upvotes: 3

Views: 5876

Answers (1)

theblindprophet
theblindprophet

Reputation: 7947

I did this two different ways:

  1. Create an array of objects, which is common

    var array = [];
    
    // ARRAY OF OBJECTS
    for(i in data) {
        // Create new array above and push every object in
        array.push(data[i]);
    }
    console.log(JSON.stringify(array));
    
  2. The way you wanted (Object with array that has arrays has objects)

    // OBJECT OF ARRAYS OF ARRAYS
    var result = data["result"];
    // Create head of object, "result"
    var obj = {"result":[]};
    var smallObj = {};
    // Push objects inside array
    for(i in result) {
        var smallArray = [];
        smallArray.push(result[i]);
        // Store that array onto array og objects, which in this case is array of arrays of objects
        smallObj[i] = smallArray;
    }
    // Final result
    obj["result"].push(smallObj);
    console.log(JSON.stringify(obj));
    

Here is the JSFiddle so you can see the stringified version printed in the console: https://jsfiddle.net/0Loh0ucm/

Upvotes: 2

Related Questions