Ron Ron - 6 months ago 20
Javascript Question

dynamically create a javascript/jquery multilevel array

This is driving me crazy.

Assuming I have this:

var tags = ["art","wedding"];
var containers = ["artcon","weddingcon"];
var limits = [5,15];


How can I create this type of multilevel array like this structure?

var testarr = [
"art" = [
"container" = "artcon",
"limit" = 5,
],
"wedding" = [
"container" = "weddingcon",
"limit" = 15,
]
];


Best regards.

Answer

You can use Array#reduce and return object

var tags = ["art", "wedding"];
var containers = ["artcon", "weddingcon"];
var limits = [5, 15];

var result = tags.reduce((res, e, i) => {
  res[e] = {container: containers[i], limit: limits[i]}
  return res;
}, {})

console.log(result)