Use dot notation property to get the object get value by key in JavaScript. obj["a"]
is equivalent to obj.a
so use obj[name]
you get “A“.
var obj = {
a: "A",
b: "B",
c: "C"
}
console.log(obj.a); // return string : A
JavaScript objects get value by key
Simple example code.
var myObject = {
'DateOfBirth' : '06/11/1978',
'Phone' : '770-786',
'Email' : '[email protected]' ,
'Ethnicity' : 'Declined' ,
'Race' : 'OtherRace'
};
var race = myObject.Race;
console.log(race)
Output:
If the Objects are inside an array var ArrayValues = [{object}, {object}, ...];
then regular array accessors will work:
var raceName = ArrayValues[0].Race;
Or, if you want to loop over the values:
for (var i = 0; i < ArrayValues.length; i++) {
var raceName = ArrayValues[i].Race;
}
Or use
const person = {
name: 'Bob',
age: 47
}
Object.keys(person).forEach((key) => {
console.log(person[key]); // 'Bob', 47
});
Source: stackoverflow.com
Get JS object keys
ar myObj = {name:'John',age:45}
var keys = Object.keys(myObj);
console.log(keys)
Output: [ “name”, “age” ]
Do comment if you have any doubts or suggestions on this Js object topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version