0

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?

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

This only works, if I am looking for key1, what if I was looking for child1 or key2?
see updated code snippet. This can be a way to do it.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.