I am trying to create an array of objects from the sample response received as const val
with dynamic keys and values. I followed this which helped me with dynamic key columns; but I am unable to dynamically assign the values to the keys.
const key
is dynamic and val.dims would always contain the exact same number of objects as the number of values in key. If key has 3 candidates; val would contain 3 objects.
I don’t want to achieve this by hardcoding if possible.
const val = {
"dims": [{
"flOne": {},
"values": [
100,
99,
98,
97,
96
]
},
{
"flOne": {},
"values": [
1,
2,
3,
4,
5
]
}
]
};
const keys = ['a', 'b'];
const lenOne = keys.length;
const base = val.dims[0].values;
const lenTwo = base.length;
console.log(lenOne, lenTwo);
const data = [];
let obj = {};
for (let i = 0; i < lenTwo; i++) {
const vals = base
keys.forEach(
(a, j) => {
obj[a] = vals[i];
return obj;
}
)
data.push(obj);
}
console.log(data);
I desire this
[{ a: 1, b:100 }, { a: 2, b: 99 }, { a: 3, b: 98 }, { a: 4, b: 97 }, { a: 5, b: 96 }]
2
Answers
There are many ways to achieve this, using
reduce
is what comes to mind:You can use map and for loop to achieve this