I am relatively new to Javascript. I am struggling with data wrangling. I would like to avoid loops.
I need to keep the higher levels of structure of "data_1", but insert an object in place of each of the key values of the form {name: "Key n", length: int}
The objects have of the following structures:
const data_1 = {
Category1: ["Key A", "Key B", "Key C"],
Category2: ["Key D", "Key E", "Key F"],
Category3: ["Key G", "Key H"]
}
const data_2 = {
"Key A": 100,
"Key B": 200,
"Key C": 300,
"Key D": 400,
"Key E": 400,
"Key F": 300,
"Key G": 200,
"Key H": 100
}
The target structure should be:
result = {
Category1: [{name:"Key A", length:100}, {name:"Key B", length:200}, {name: "Key C", length:300}],
Category2: [{name:"Key D", length:400}, {name:"Key E", length:400}, {name: "Key F", length:300}],
Category3: [{name:"Key G", length:200}, {name:"Key H", length:100}]
}
I suspect the way to tackle this is something akin to the following pseudo code. I am struggling to define an object as [name: key, length:data_2.key] .
let results = Object.fromEntries(data_1.map(key => [name: key, length:data_2.key]));
Any and all help is appreciated :)
A reduce will do the trick and be quite readable too
const result = Object.entries(data_1).reduce((acc, [key, vals]) => {
acc[key] = vals.map(val => ({ name: val,length: data_2[val] }));
return acc;
}, {});
console.log(result);
<script>
const data_1 = {
Category1: ["Key A", "Key B", "Key C"],
Category2: ["Key D", "Key E", "Key F"],
Category3: ["Key G", "Key H"]
}
const data_2 = {
"Key A": 100,
"Key B": 200,
"Key C": 300,
"Key D": 400,
"Key E": 400,
"Key F": 300,
"Key G": 200,
"Key H": 100
}</script>
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