A
A
Alexey Yarkov2018-05-14 16:56:03
JavaScript
Alexey Yarkov, 2018-05-14 16:56:03

How to convert the keys of an object of the form "key[index]" to an array?

Gentlemen, how to kosher this

{
  list: {
    "action_buttons[0]": "View",
    "action_buttons[1]": "Share",
    "action_buttons[2]": "Download",
    "columns[0]": "Date of Study",
    "columns[1]": "Patient",
    "columns[2]": "File name",
    "columns[3]": "Reporting <br>Physician",
    "columns[4]": "Institution"
  }
}

in
{
  list: {
    "action_buttons": [
      "View", "Share", "Download"
    ],
    "columns": [
      "Date of Study", "Patient", "File name", "Reporting <br>Physician", "Institution" 
    ]
  }
}

Maybe there is some method in lodash? I can't find.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2018-05-14
@yarkov

var t = {
  list: {
    "action_buttons[0]": "View",
    "action_buttons[1]": "Share",
    "action_buttons[2]": "Download",
    "columns[0]": "Date of Study",
    "columns[1]": "Patient",
    "columns[2]": "File name",
    "columns[3]": "Reporting <br>Physician",
    "columns[4]": "Institution"
  }
};

var list = {};
var re = /^(.*?)\[(\d+)\]$/;
var match;
for (var prop in t.list) {
  match = prop.match(re);
  if (typeof list[match[1]] == "undefined") {
    list[match[1]] = [];
  }
  list[match[1]][match[2]] = t.list[prop];
}
t.list = list;
console.log(t);

{…}
​   list: {…}
​​      action_buttons: […]
​​​         0: "View"
​​​         1: "Share"
​​​         2: "Download"
​​​      columns: […]
​​​         0: "Date of Study"
​​​         1: "Patient"
​​​         2: "File name"
​​​         3: "Reporting <br>Physician"
​​​         4: "Institution"
​

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question