访问对象中的键以在函数

时间:2017-05-17 05:41:26

标签: javascript object nested

我有一个嵌套对象:

myObj = {
   id:'AA',
   child:{
      id:'BB',
      key1:'CC'
   },
   child2:{
      id:'DD',
      key1:'EE'
   },

};

我还有一个功能,我目前正在这样做:

doSomething = function(id,childid,key){
  var str = id + childid + key;
  console.log(str);
};
doSomething(myObj.id,myObj.child.id,myObj.child.key1);

我想简化一下:

doSomething2 = function(incObj){
  //myObj.child.key1;
  var str = incObj.id + ' ' + incObj.child.id + ' ' + incObj.child.key;
  //str = 'AA BB CC';
   console.log(str);

}
doSomething2(myObj.child.key1);

这样做有干净/简单的方法吗?

2 个答案:

答案 0 :(得分:0)

你已经找到了自己的答案。你只需要传递对象即可。

对象:

myObj = {
   id:'AA',
   child:{
      id:'BB',
      key1:'CC'
   },
   child2:{
      id:'DD',
      key1:'EE'
   },

};

功能:

doSomething2 = function(incObj){
  //myObj.child.key1;
  var str = incObj.id + ' ' + incObj.child.id + ' ' + incObj.child.key1;
   console.log(str);

}
doSomething2(myObj);

答案 1 :(得分:0)

你这样做的方式:



myObj = {
   id:'AA',
   child:{
      id:'BB',
      key1:'CC'
   },
   child2:{
      id:'DD',
      key1:'EE'
   },

};

doSomething2 = function(incObj){
  //myObj.child.key1;
  var str = incObj.id + ' ' + incObj.child.id + ' ' +incObj.child.key1;
  //str = 'AA BB CC';
   console.log(str);

}
doSomething2(myObj);






myObj = {
   id:'AA',
   child:{
      id:'BB',
      key1:'CC'
   },
   child2:{
      id:'DD',
      key1:'EE'
   },

};

var config = {
  "child" : "child2",
  "key" :"key1"
}

doSomething2 = function(incObj, config){
  //myObj.child.key1;
  var str = incObj.id + ' ' + incObj[config.child].id + ' ' +incObj[config.child][config.key];
  //str = 'AA BB CC';
   console.log(str);

}
doSomething2(myObj,config);