Heather Heather - 11 months ago 41
Javascript Question

How to change a Javascript nested object in object to an indexed array?

I'm fairly new to developing, so need some help with an object. I tried doing a for loop and pushing the values into an array. The problem is that it is pushing all the keys/values as one index rather than indexing each key/value separately. I am working with a key/value object as follows:

var obj = {
"application": {
"create": "false",
"read": "true",
"update": "true",
"delete": "false"
},
"connection": {
"create": "false",
"read": "true",
"update": "true",
"delete": "false"
}
}


I need each key(application and connection) to be indexed - the keys need to be values. For example the following would retrieve:

obj[0] = application
obj[0].create = false
obj[1] = connection


Thanks for your help.

Answer Source

You can add an extra field key to store the keys of the object obj. This is produce an array of objects.

var obj = {
  "application": {
    "create": "false",
    "read": "true",
    "update": "true",
    "delete": "false"
  },
  "connection": {
    "create": "false",
    "read": "true",
    "update": "true",
    "delete": "false"
  }
}

var keys = Object.keys(obj)
var arr = []
keys.map(function(key, i) {
  arr[i] = obj[key]
  arr[i].key = key
})

console.log(arr[0].key)
console.log(arr[0].create)
console.log(arr[1].key)