2

I have following nested configuration object, and I want to get the value of key1, which means I want to return "value1", key1 is static, but randomGeneratedNumber and randomGeneratedName are dynamic from database.

configuration:{
 randomGeneratedNumber:
   {
       randomGeneratedName:
          {
            key1: value1,
            key2: value2
          }
    }
}
2

3 Answers 3

2

If you know you have (at least) one key at each level, you can do it with a helper function and composition:

var obj = {
  configuration: {
    randomGeneratedNumber: {
      randomGeneratedName: {
        key1: 'value1',
        key2: 'value2'
      }
    }
  }
};

function firstValue(a) {
  return a[Object.keys(a)[0]];
}

console.log(firstValue(firstValue(obj.configuration)).key1);

Or if you have a dynamic (but known) depth, you can do it with recursion:

var obj = {
  configuration: {
    randomGeneratedNumber: {
      randomGeneratedName: {
        key1: 'value1',
        key2: 'value2'
      }
    }
  }
};

function firstValueDeep(a, depth) {
  var keys = Object.keys(a);
  if (+depth <= 0 || !keys.length) {
    return a;
  } else {
    return firstValueDeep(a[keys[0]], depth - 1);
  }
}

console.log(firstValueDeep(obj.configuration, 2).key1);

Beyond that, you'll want to look into graph traversal algorithms, like depth-first-search or breadth-first-search, to find some object having 'key1' as a property.

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

Comments

0

Dynamically you can do this.. i'm hoping this helps or gives you an head way towards the problem. :)

var config = {configuration:{
 randomGeneratedNumber:
   {
       randomGeneratedName:
          {
            key1: "value1",
            key2: "value2"
          }
    }
}};

let configKeys = Object.keys(config.configuration);
configKeys.forEach((rand)=>{
	console.log(rand);
	var itemKeys = Object.keys(config.configuration[rand]);
  console.log(itemKeys);
  for(var i=0;i<itemKeys.length;i++){
  	let randName = itemKeys[i];
  	console.log(config.configuration[rand][randName]['key1']);
    console.log(config.configuration[rand][randName]['key2']);
  }
});

Comments

0

If I understand the question, I would just do something like this:

let value;
for (let nestedOuter of Object.values(something.configuration))
    for (let nestedInner of Object.values((nestedOuter)))
        value = nestedInner.key1;
console.log(value);

If you need the randomly generated values, you'll need to do Object.entries instead to pull out both key and value.

1 Comment

Sorry, I remembered the syntax wrong. It should work now.

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.