简体   繁体   中英

Accessing keys within Objects for use in a function

I have a nested object:

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

};

I also have a function where I am currently doing this:

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

I would like to simplify to this:

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

Is there a clean/simple way of doing this?

You've already found the answer by yourself. You just have the pass the object and it's done.

Object:

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

};

function:

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

}
doSomething2(myObj);

The way you doing it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM