Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

javascript - Access nested object dynamically by using array of string as a path

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"]));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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" ] ) );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...