Access nested object dynamically by using array of

2020-04-01 13:20发布

问题:

I'm trying to implement a generic method to access a nested object property dynamically.

The path to the property have to be in an array of string.

So to get the label the array of string would be ['type', 'label']

I'm kinda stuck on this problem, any help ?

**Edit snipet : **

Demo

var parent = {
  type: {
    id: "2",
    label: "3",
  }
};

function getNestedLabel(ids){
if (ids.length === 1) {
  return parent[ids[0]];
}
var result = parent;
for (let i = 0; i < ids.length; i++) {
  result = result[ids[i]];
}
return result;
  }

console.log(getNestedLabel(["type", "label"]));

回答1:

A simple approach would be to iterate the keyArray and also keep traversing the object with keys from keyArray

function getNestedObject( keyArr ){
    var tmp = parent; //assuming function has access to parent object here
    keyArr.forEach( function(key){
       tmp = tmp[key];
    });
    return tmp;
}

Demo

var parent = {
  type: {
    id: "2",
    label: "3",
  }
};

function getNestedObject(keyArr) {
  var tmp = parent; //assuming function has access to parent object here
  keyArr.forEach(function(key) {
    tmp = tmp[key];
  });
  return tmp;
}

console.log( getNestedObject( [ "type", "label" ] ) );



回答2:

what about this:

getNestedObject(parent: any, id:string[]): string{

    let child = {...parent};
    let result: string;
    for(let i=0; i<id.length; i++){
        if( i !== id.length-1 ){
            child = child[id[i]]
        }
        else{
            result = child[id[i]]
        }
    }
    return result;
}