将嵌套对象推送到数组

时间:2016-04-05 01:11:57

标签: arrays json object

如何将嵌套的json对象推入数组。 这是示例json对象。假设我有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,
        }
    }
}

示例输出如下:

"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,
        }
    }]
}] 

我不知道该怎么做。如果简单的对象,我可以这样推:

var arr=[];

arr.push(数据);

推入阵列的原因,因为组的关键对象是动态的。我想用group来过滤数据。

1 个答案:

答案 0 :(得分:1)

我做了两种不同的方式:

  1. 创建一个对象数组,这是常见的

    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. 您想要的方式(包含数组的数组的对象具有对象)

    // 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));
    
  3. 这是JSFiddle,因此您可以看到控制台中打印的字符串化版本:https://jsfiddle.net/0Loh0ucm/