【问题标题】:Best way to split a large JSON response into multiple objects and push them to an array将大型 JSON 响应拆分为多个对象并将它们推送到数组的最佳方法
【发布时间】:2020-08-01 10:32:45
【问题描述】:

我有一个很大的 JSON 响应,在 HTTP 调用后返回,如下所示:

0: { index: 0, name: "bob", age: 12, location: "adelaide" ... }
1: { index: 0, name: "jeff", age: 23 ... }
2: { index: 1, name: "sam", age: 25 ... }
...

由此,我想创建一个对象数组,每个对象对应 index 的每个值及其对应的条目,我可以在其中选择将哪些数据放入这些条目中。像这样的:

[
    { name: "index_0", index: 0, data: [{ name: "bob", age: 12  }, { name: "jeff", age: 23 }] },
    { name: "index_1", index: 1, data: [{ name: "sam", age: 25 }] },
    ...
]

我知道我需要根据索引计数在此处动态创建对象,但我不确定如何执行此操作。

【问题讨论】:

    标签: javascript arrays json


    【解决方案1】:
    const newdata = [];
    origdata.forEach(function(item){
        if(!newdata[item.index])
            newdata[item.index] = {name:'index_'+item.index,index:item.index,data:[]};
        newdata[item.index].data.push(item);
        delete item.index;
    });
    

    【讨论】:

    • 非常感谢。我遇到的一个问题是,当我对原始数据运行 forEach 函数时,项目是整个数组而不是其中的每个单独项目。当我打印它时,它看起来像这样: test : [object Object],[object Object],[object Object],[object Object]..... 我应该在运行 forEach 之前先转换这个响应吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-13
    • 2011-08-06
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    • 2023-04-10
    • 2018-07-27
    相关资源
    最近更新 更多