Home > Enterprise >  How to get value from an object property? [closed]
How to get value from an object property? [closed]

Time:10-05

I have an object key which looks something like:

{key: '1#436bdhsdas73hb2hj/472326badh}

How do i get the value of key here.[The object's name is also key and the property here is also called key.]

CodePudding user response:

In general you would get a property value like this:

// Store the object in a variable
let object = {
 key: 'value'
};

// Retrieve the property value
object.key;

You can also log the property to see the value in the browser's console:

// Log the property value
console.log(object.key);

CodePudding user response:

You can use the below code

var key = 'key-name';
var obj = {
  'key-name': 'key-value'
};
console.log(obj[key]);

CodePudding user response:

Answer:
In your case, you mentioned the object name and returned object's key name are same. So it should be as follows:

var key = {key: '1#436bdhsdas73hb2hj/472326badh'}

then call key.key you will get 1#436bdhsdas73hb2hj/472326badh

Note:
A single quote at the end (for the value) is missing in your post.

var obj = {key: '12345'};

function showKeyInObject(){
  alert(obj.key)
}
<button onClick="showKeyInObject()">Click me</button>

Best reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

If you want to loop through keys/values:

const obj = {key1: 'one', key2: 'two', key3: 'three'};

for(let key in obj){
    console.log('Key: ', key, ' | value: ', obj[key]);
}
  • Related