简体   繁体   中英

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.

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)

If you want each property of the object pushing into an array, you can iterate over the object contents like so:

for (var item in obj){
    /* item will equal the first property of obj, in this case: 'application' */
    array.push(item)
}

array = ["application", "connection"]

You can use the same technique on each object property, to index their children into the array.

By the outcome you expect, it looks like you want to transform the first level of your object to array cells.

This will do it:

var arr = [], i=0;
for (var key in obj) {
   arr[key] = obj[key] // For accessing via the property name for example e.g. application
   arr[i] = obj[key] // For index access for example obj[0]
   i++;
}

You can also use the .map method to do it.

You could iterate over the keys and assamble a new array with the children of the inner object.

 var obj = { application: { create: "false", read: "true", update: "true", delete: "false" }, connection: { create: "false", read: "true", update: "true", delete: "false" } }, array = Object.keys(obj).map(function (k) { return [k].concat(Object.keys(obj[k]).map(function (kk) { return obj[k][kk]; })); }); console.log(array);

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