简体   繁体   中英

How do I turn this object of objects into an array of objects

This is my object that contains 3 objects.

{
    "costco":
        {
            "costco_11":{"id":1, "address":"123 main"}, 
            "costco_12":{"id":2, "address":"345 Oak"},
            "costco_13":{"id":3, "address":"789 Birch"}
        }
}

I would like to create a single array that contains 3 objects so that I can dynamically create some ListView items in React-Native.

I would like to avoid using Lodash(Probably not needed, but I just want to make sure since I mentioned react-native)

I would like to create a single array that contains 3 objects

Simply get Object.values

var obj = {
     "costco":{
         "costco_11":{"id":1, "address":"123 main"}, 
         "costco_12":{"id":2, "address":"345 Oak"},
         "costco_13":{"id":3, "address":"789 Birch"}
      }
};
obj.costco = Object.values(obj.costco);
console.log(obj);

There is no need for external libs; you can do it in plain Javascript.

let myObj =  {"costco":{
         "costco_11":{"id":1, "address":"123 main"}, 
         "costco_12":{"id":2, "address":"345 Oak"},
         "costco_13":{"id":3, "address":"789 Birch"}
      }
};

let myArray = Object.values(myObj.costco);

I made a little fiddle for this.

const newArr = Object.keys(fakeOb).map(function(k) { return fakeOb[k]});
console.log(newArr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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