Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript: Mapping values from one array to keys within a multidimational array

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 🙂

>Solution :

If we grab the entries, we can map over the keys and get each of them like this. Then we can create an object from the transformed entries.

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
};

const data_3 = Object.fromEntries(
    Object.entries(data_1)
        .map(([cat, keys]) => [cat, keys.map((key) => ({ name: key, length: data_2[key] }))]
    )
);

console.log(data_3);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading