简体   繁体   English

将多个JSON的数据附加到一个object

[英]Appending data from multiple JSON to one object

I got 31 json files in 'pl' folder, named 'objects_p=1', 'objects_p=2' etc. Each contains 50 values, except the last (24 values).我在“pl”文件夹中有 31 个 json 文件,分别命名为“objects_p=1”、“objects_p=2”等。每个文件包含 50 个值,除了最后一个(24 个值)。 Trying to fetch all data into one object:试图将所有数据提取到一个 object 中:

let sourceObj={};

for (let i=1;i<32;i++){
        fetch(`pl/objects_p=${i}`)
            .then((response) => response.json())
            .then((data) => {
                let new_obj = Object.assign(sourceObj,data);
                sourceObj = new_obj
                });
    }

So basically, I try to append data to newObj in loop.所以基本上,我尝试在循环中将 append 数据发送到 newObj。 But when console.logging sourceObj, i got only last 24 values instead expected 1524. Where's the mistake?但是当 console.logging sourceObj 时,我只得到了最后 24 个值而不是预期的 1524。错误在哪里?

Object.assign simply replace the values if the attributes already exist. Object.assign 如果属性已经存在,只需替换值。 It does only work with different values Mozilla doc它只适用于不同的值Mozilla 文档

From the link:从链接:

 const target = { a: 1, b: 2 }; const source = { b: 4, c: 5 }; const returnedTarget = Object.assign(target, source); console.log(target); // Expected output: Object { a: 1, b: 4, c: 5 } console.log(returnedTarget === target); // Expected output: true

Edit编辑

Object can not have duplicated properties, you can maybe simply use an array to store all of your objects Object 不能有重复的属性,你可以简单地使用一个数组来存储你所有的对象

let sourceObj={};
let allSources=[sourceObj].

for (let i=1;i<32;i++){
        fetch(`pl/objects_p=${i}`)
            .then((response) => response.json())
            .then((data) => {
                allSources.push(data)
                });
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM