noyruto88
noyruto88

Reputation: 907

How to get the property name of object and use that property name in javascript

I have an object named: mapped_errors that returns a dynamic object.

sometimes its value is:

{ _id:
   { location: 'body',
     param: '_id',
     value: 123,
     msg: '_id is required and must be a string' } }

and sometimes its value is:

{ _name:
   { location: 'body',
     param: '_name',
     value: 123,
     msg: '_name is required and must be a string' } }

and i want to output the msg value something like this:

let obj_key = Object.keys(mapped_errors);
console.log(mapped_errors.{obj_key}.msg); // i know this is wrong

;-)

Upvotes: 2

Views: 5416

Answers (5)

Joven28
Joven28

Reputation: 769

let obj = { _id:
   { location: 'body',
     param: '_id',
     value: 123,
     msg: '_id is required and must be a string' } }

console.log(obj[Object.keys(obj)[0]].msg)

Upvotes: 0

Shalitha Suranga
Shalitha Suranga

Reputation: 1146

You can use Object.keys with index as per below

mapped_errors = { _id:
   { location: 'body',
     param: '_id',
     value: 123,
     msg: '_id is required and must be a string' } };
     
console.log(mapped_errors[Object.keys(mapped_errors)[0]].msg);     
     
mapped_errors = { _name:
   { location: 'body',
     param: '_name',
     value: 123,
     msg: '_name is required and must be a string' } };

console.log(mapped_errors[Object.keys(mapped_errors)[0]].msg);

Object.keys returns the array of keys [0] will take first key and mapped_errors[Object.keys(mapped_errors)[0]].msg will return msg content.

Upvotes: 0

Mawcel
Mawcel

Reputation: 2007

You can check if the property exists mapped_errors.hasOwnProperty('_name')

You coud also access the first key like so: var keys = Object.keys(mapped_errors); console.log(mapped_errors[keys[0]])

Hope this helps

Upvotes: 0

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

The only error in your code is mapped_errors.{obj_key}.msg. You should be using [] to access the object's property value when you are using a variable to get the key name, as mapped_errors[obj_key].

var mapped_errors = { _id:
   { location: 'body',
     param: '_id',
     value: 123,
     msg: '_id is required and must be a string' } };

let obj_key = Object.keys(mapped_errors);
console.log(mapped_errors[obj_key].msg);

mapped_errors = { _name:
   { location: 'body',
     param: '_name',
     value: 123,
     msg: '_name is required and must be a string' } }
     
obj_key = Object.keys(mapped_errors);
console.log(mapped_errors[obj_key].msg);

Upvotes: 1

hsz
hsz

Reputation: 152216

Just loop your object using its keys:

Object.keys(mapped_errors).forEach(key => {
  const value = mapped_errors[key];

  console.log(value.msg);
})

Or if you don't want to loop because there will be just one entry, try with:

const key = Object.keys(mapped_errors)[0];

console.log(mapped_errors[key].msg);

Upvotes: 0

Related Questions