Home > Enterprise >  Appending data from multiple JSON to one object
Appending data from multiple JSON to one object

Time:01-19

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). Trying to fetch all data into one 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. But when console.logging sourceObj, i got only last 24 values instead expected 1524. Where's the mistake?

CodePudding user response:

Object.assign simply replace the values if the attributes already exist. It does only work with different values Mozilla doc

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

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)
                });
    }
  • Related