I tried searching through previous questions but couldn't find the answer so here's a very generic question.
I have a multidimensional array like so:
array = [
[ "1", "2013-14" , 1234],
[ "2", "2013-14", 2345],
[ "1", "2014-15" , 5234],
[ "2", "2014-15", 7345],
]
I am trying to change it to a nested object based on the year:
obj = {
"2013-14": { 1: "1234", 2: "2345" },
"2014-15": { 2: "5234", 2: "7345" }
}
I tried this, which gave a similar but wrong solution:
let obj = {}
for (let i = 0; i < array.length; i++) {
obj[array[i][1]] = {
[array[i][0]]: array[i][2]
}
}
the solution I got:
obj = {
"2013-14": { 2: "2345" },
"2014-15": { 2: "7345" }
}
so instead of concatenating values under the same key, which in this case is the year, it is overriding it and saving the last one
You need to respect the object for ech date.
const
array = [["1", "2013-14", 1234], ["2", "2013-14", 2345], ["1", "2014-15", 5234], ["2", "2014-15", 7345]],
obj = {};
for (let i = 0; i < array.length; i++) {
obj[array[i][1]] ??= {};
obj[array[i][1]][array[i][0]] = array[i][2];
}
console.log(obj);
A shorter approach with destructuring
const
array = [["1", "2013-14", 1234], ["2", "2013-14", 2345], ["1", "2014-15", 5234], ["2", "2014-15", 7345]],
obj = {};
for (const [inner, outer, value] of array) {
obj[outer] ??= {};
obj[outer][inner] = value;
}
console.log(obj);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With