0

I have a lot of values I need to extract from a JSON object called results. I have stored the keys I care about in another object myKeys.

How can I use the values from myKeys as the selector in results? Ultimately I want the data in results.array1.array2.key, results.array1.anotherThing.key, etc.

const myKeys = {
    key1: '.array1.array2.key',
    key2: '.array1.anotherThing.key',
    key3: '.array1.somethingElse.array2.key'
}

for (let [key, value] of Object.entries(myKeys)){
    let data = {name: key, results: results[value]}
}
Gerg
  • 68
  • 6

1 Answers1

2

How about splitting each key by . and then iteratively fetching the value? Something like this:

data = {}
for (key in myKeys){
  let innerKeys = myKeys[key].split(".").shift(); // yields array ['array1', 'array2', 'key']
  let result = results
  innerKeys.forEach(key => {
    result = result[key]
  });
  data[key] = result;
}

This updates your local result variable to inner object through the forEach loop, and then in the end just set the data[key] to the innermost result value. The shift() function removes the first empty element. You can omit that if you remove the first period character.

Raghav Kukreti
  • 552
  • 5
  • 18