gpt4 book ai didi

arrays - 将嵌套对象推送到数组

转载 作者:行者123 更新时间:2023-12-01 13:13:16 25 4
gpt4 key购买 nike

如何将嵌套的 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(数据);

之所以插入数组,是因为组的键对象是动态的。我想使用组来过滤数据。

最佳答案

我用两种不同的方式做到了这一点:

  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));

这是 JSFiddle,因此您可以在控制台中看到打印的字符串化版本:https://jsfiddle.net/0Loh0ucm/

关于arrays - 将嵌套对象推送到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36415483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com