While working with an array of arrays and using .map()
, I encountered a problem trying to assign the inner arrays as key-value pairs in an object. Despite several attempts, it wasn't successful. I'm wondering if I need to adjust my approach by breaking it down into more steps or using additional functions and variables.
I experimented with different syntax variations for the assignment element without any luck.
Even when trying arr.map(function() {})
syntax, there was no change in the outcome.
const smallArr = [1, 23, 25, 46, 52, 789, 64];
const thisArr = [5, 4, 65, 24, 35];
const thatArr = [{key: 1, anotherKey: 2}];
let parentObj = {};
const bigArr = [smallArr, thisArr, thatArr];
const newSomething = bigArr.map(arr => parentObj["arr"] = arr);
// The current parentObj output is: { arr: [ { key: 1, anotherKey: 2 } ] }
The issue seems to be related to the string representation of the element being assigned every iteration, leading to overwriting values. Consequently, the final object contains only one key-value pair, where the value corresponds to the last inner array in the outer array.
const newSomething = bigArr.map(arr => parentObj.arr = arr);
// returns { arr: [ { key: 1, anotherKey: 2 } ] }
const newSomething = bigArr.map(arr => parentObj['arr'] = arr);
// returns { arr: [ { key: 1, anotherKey: 2 } ] }
I am particularly puzzled by the behavior in the last example.
const newSomething = bigArr.map(arr => parentObj[`${arr}`] = arr);
// returns {
'1,23,25,46,52,789,64': [ 1, 23, 25, 46, 52, 789, 64 ],
'5,4,65,24,35': [ 5, 4, 65, 24, 35 ],
'[object Object]': [ { key: 1, anotherKey: 2 } ],
arr: [ { key: 1, anotherKey: 2 } ]
}
The following example leaves me completely perplexed.
const newSomething = bigArr.map(arr => parentObj["`${arr}`"] = arr);
// returns {
'`${arr}`': [ { key: 1, anotherKey: 2 } ],
arr: [ { key: 1, anotherKey: 2 } ]
}
My goal is to achieve the following structure:
parentObj = {
smallArr: [1, 23, 25, 46, 52, 789, 64],
thisArr: [5, 4, 65, 24, 35],
thatArr: [{key: 1, anotherKey: 2}],
}