skip to Main Content

I have an object that has some other objects inside. I want to put all of these inside objects into an array.

I tried for loop and in each iteration I would push those objects into an array. The problem is that when I log the array, after the for loop finished ,it would have only the last inserted object. I assume every new iteration would set a new array and in process kinda the previous array would be erased.

Right now I can’t provide any code. But soon I put everything in a repo and shared here.

Thanks

2

Answers


  1. Hope this will help

    let objectA = {a: 'value A'}
    let objectB = {b: 'value B'}
    let objectC = {c: 'value C'}
    
    let obj = {objectA, objectB, objectC}
    
    let output = [];
    
    for (let value of Object.values(obj)) {
      output.push(value);
    }
    
    console.warn(output)

    Try to create array outside of the loop to prevent your case

    Object.values will return an array containing object’s value of each key. If you want both key and value, you can use Object.entries instead

    Login or Signup to reply.
  2. You can use Object.values.

    const obj = {
      objectA: { a: "898738" },
      objectB: { b: "123123" },
      objectC: { c: "23122321" },
    };
    const output = Object.values(obj);
    
    console.log({ output });
    .as-console-wrapper { min-height: 100%!important; top: 0; }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search