This is my JSON file:
{
"Key": "some-key",
"some-key": {
"comLength": 1
},
}
How do I access the comLength
value?
This is my JSON file:
{
"Key": "some-key",
"some-key": {
"comLength": 1
},
}
How do I access the comLength
value?
I would do this
Considering your object variable is named someObject
, you can access it like:
var comLength = someObject["some-key"].comLength
Example:
var someObject = {
"Key": "some-key",
"some-key": {
"comLength": 1
},
}
var comLength = someObject["some-key"].comLength;
console.log(comLength);
You can reference it via the dot notation (.) and the square notation ([]) (the [] notation is mandatory in case of the property key of some-key
because of the -
)
const obj = {
"Key": "some-key",
"some-key": {
"comLength": 1
}
};
console.log(obj["some-key"].comLength);
console.log(obj["some-key"]["comLength"]);
If you dont know the key but know the property you want inside the key then looping might help
var my_obj = {
Key: "some-key",
"some-key": {
comLength: 1,
},
};
// the name of the property you want
property = "comLength";
for (item in my_obj) {
// checks if the the property exists
if(my_obj[item].hasOwnProperty(property)){
console.log(my_obj[item][property]);
}
}
Gives output
1
const json = {
"Key": "some-key",
"some-key": {
"comLength": 1
},
}
var key1 = 'some-key';
var key2 = 'comLength';
const value = json[key1][key2];