skip to Main Content

I have an object like this from an api.

{
  "32111" { ...object}
  "83276" { ...object}
...
}

How can I convert this to an array for each number ?

like this


[
{
id: "32111"

},
{
id: "83276"
}
]


The api gives me only a whole object of strings with ids but not a array. How can I convert this to an array?

2

Answers


  1. You can map the keys to new compound objects:

    const object = {prop1: 1, prop2: 2};
    const data = {
      "32111" : { ...object},
      "83276" : { ...object}
    }
    
    const result = Object.keys(data).map(id => ({id, ...data[id]}));
    
    console.log(result);
    Login or Signup to reply.
  2. You can use static Object methods.

    const obj = {   
       "32111":  { "name": "One" }
       "83276":  { "name": "Two }
    }
    const keys = Object.keys(obj) // ["32111", "83276"]
    const values = Object.values(obj) // [value, value]
    const entries = Object.entries(obj) 
    // [
    //    ["32111", { "name": "One" }],
    //    ["83276",  { "name": "Two }]
    //
    

    Then you can operate on them as Arrays.

    entries.map(...)
    keys.forEach(...) 
    //...etc
    
    const obj = {   
       "32111":  { "name": "One" },
       "83276":  { "name": "Two" }
    }
    const keys = Object.keys(obj); // ["32111", "83276"]
    const values = Object.values(obj); // [value, value]
    const entries = Object.entries(obj); 
    
    // [
    //    ["32111", { "name": "One" }],
    //    ["83276",  { "name": "Two }]
    // ]
    
    
    console.log(entries.map(([key,value]) => `${key} is "${JSON.stringify(value)}"`))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search