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
          }
    }
}
Elizabeth
  • 47
  • 9

3 Answers3

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.

tavnab
  • 2,594
  • 1
  • 19
  • 26
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.

Brett Beatty
  • 5,690
  • 1
  • 23
  • 37
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']);
  }
});
Paul Okeke
  • 1,384
  • 1
  • 13
  • 19