简体   繁体   中英

How to change nested object into array

I have a object like this.

var Obj = {
    obj1 : {
        val : 1,
        id : 1
    }
    obj2 : {
        val : 2,
        id :2
    }
    obj3 : {
        val : 3,
        id :3
    }
}

I want my obj1 and all sub object into one array so I can retrieve the value. I want array in array because I want to retrieve them, Since it is dynamic I can not use Obj.obj1 therefore I want to push into array.

Can Anybody tell How Can I get that. Thanks for help

Use Object.keys and Array#map methods to convert it to an array but the order is not guaranteed since object properties don't have any order.

 var Obj = { obj1: { val: 1, id: 1 }, obj2: { val: 2, id: 2 }, obj3: { val: 3, id: 3 } }; var res = Object.keys(Obj).map(function(k) { return Obj[k]; }) console.log(res); 

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