Skip to content Skip to sidebar Skip to footer

How To Get Proprety Value Of Object From Parent Object

I have object in this structure: obj = { user: { name: 'jeterson' }, title: 'I am a test' } I have one key with value: user.name. I have trying get value like this: obj[ke

Solution 1:

You can access it with:

obj['user']['name']

Or alternatively:

obj.user.name

If you want to get from a key like "user.name" to the value, you woulr have to do some logic yourself. You could hack something together like this:

let obj = {
  user: {
    name: 'jeterson'
  },
  title: 'I am a test'
}

let key = 'user.name';
let keys = key.split('.');

let res = obj;
while (keys.length > 0 && res) {
  let k = keys.shift();
  res = res[k];
}
console.log(res) // "jeterson"

When the keys do not match, res holds undefined.


Solution 2:

You've got multiple solutions to access an element of an object with its keys:

var obj = {
  user: { name: 'jeterson' },
  title: 'I am a test'
}

console.log(obj['user']['name']);
console.log(obj['user'].name);
console.log(obj.user['name']);
console.log(obj.user.name);

But you can't do it easily with a variable key = 'user.name'.

If you need to use a variable containing the nested-keys, you could create a function.

Updated answer: An amazingly short way to achieve it is to use .reduce():

// My function
function obj_tree_key(obj, path) {
 return path.split('.').reduce((accu, val) => accu[val] || 'Not found', obj);
}

var obj1 = {
  user: {
    name: 'jeterson'
  },
  title: 'I am a test'
}
console.log(obj_tree_key(obj1, 'user.name')); // Outputs "jeterson"

// Here is an example with error:
var obj2 = { 
  user: {
    nameeeee: 'jeterson'
  },
  title: 'I am a test'
}
console.log(obj_tree_key(obj2, 'user.name'));

Old answer: Use a for to loop through the keys and reduce the oject:

// My function
function obj_tree_key(obj, tree_key) {
  var result = obj;
  var keys = tree_key.split('.');
  for (var i = 0; i < keys.length; i++) {
    result = result[keys[i]] || 'Not found'; // Error handling
  }
  return result;
}

var obj1 = {
  user: {
    name: 'jeterson'
  },
  title: 'I am a test'
}
console.log(obj_tree_key(obj1, 'user.name')); // Outputs "jeterson"

// Here is an example with error:
var obj2 = { 
  user: {
    nameeeee: 'jeterson'
  },
  title: 'I am a test'
}
console.log(obj_tree_key(obj2, 'user.name'));

Hope it helps.


Solution 3:

first get the user, then the name:

obj['user']['name']

or

obj.user.name

Solution 4:

You can also use obj.user.name


Solution 5:

You could access it using

console.log(obj.user.name);

Post a Comment for "How To Get Proprety Value Of Object From Parent Object"