2

I have an array which includes some keys and subkeys of the object:

let keysArray = ['Computer Technics', 'Laptops', 'Lenovo', 'Ideapads',];

And also I have an object:

let obj = {
    'Computer Technics': {
        'Laptops': {
            'Lenovo': {
                'Ideapads': "data"
            }
        }
    }
};

I need to get a link to the "data":

obj['Computer Technics']['Laptops']['Lenovo']['Ideapads']

I can't understand how to do that..

I mean I wrote a function which creates a link itself, but I have no idea how to connect it with obj

console.log(obj[getKey(keysArray)]); // obviously undefined as a result is put into '[]'
console.log(obj+getKey(keysArray)); //obviously it doesn't work too

function getKey(arr) {
    let res = '';
    for (i = 0; i < arr.length; i++) {
        res = res + '[\'' + arr[i] + '\']';
    }
    return res;
}

Any help will be appreciated a lot! Thanks!

  • Possible duplicate of [Accessing nested JavaScript objects with string key](https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key) – adiga Jul 11 '19 at 16:33
  • `keysArray.reduce((a, k) => a[k], obj)` – adiga Jul 11 '19 at 16:35

3 Answers3

0

you can try this

var pointer = obj;
for ( key of keysArray) { pointer = pointer[key]} ;
console.log(pointer);
ashish singh
  • 6,526
  • 2
  • 15
  • 35
0

You can do something like this:

let keysArray = ['Computer Technics', 'Laptops', 'Lenovo', 'Ideapads',];

let obj = {
    'Computer Technics': {
        'Laptops': {
            'Lenovo': {
                'Ideapads': "data"
            }
        }
    }
};

const value = keysArray.reduce((a, c) => a[c], obj);
console.log(value);
Titus
  • 22,031
  • 1
  • 23
  • 33
0

You can use object references

let keysArray = ['Computer Technics', 'Laptops', 'Lenovo', 'Ideapads',];

let obj = {
    'Computer Technics': {
        'Laptops': {
            'Lenovo': {
                'Ideapads': "data"
            }
        }
    }
};

let getData = (arr,obj) => {
  let output = JSON.parse(JSON.stringify(obj));
  arr.forEach(val => {
    output = output && output[val]
  })
  return output
}

console.log(getData(keysArray,obj))
Code Maniac
  • 37,143
  • 5
  • 39
  • 60