Search code examples
javascriptarraystypescriptobject

How to put an object's items into an array?


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


Solution

  • 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)) {
      // Filter here if needed
      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