0

This is my JSON file:

{
 "Key": "some-key",
        "some-key": {
        "comLength": 1
        },
}

How do I access the comLength value?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303

5 Answers5

0

I would do this

  1. parse to custom object
  2. do a For-loop by the required property
  3. break the loop as soon I found the match
vargashj
  • 33
  • 6
0

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);
Ganesh Sanap
  • 1,386
  • 1
  • 8
  • 18
0

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"]);
Ran Turner
  • 14,906
  • 5
  • 47
  • 53
0

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
Balaji
  • 795
  • 1
  • 2
  • 10
0
const json = {
  "Key": "some-key",
  "some-key": {
    "comLength": 1
  },
}

var key1 = 'some-key';
var key2 = 'comLength';

const value = json[key1][key2];
Pramisha C P
  • 319
  • 2
  • 6
  • 1
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. You can find more information on how to write good answers in the help center: https://stackoverflow.com/help/how-to-answer . Good luck – nima Oct 23 '21 at 21:45