skip to Main Content

I used jsonData[‘some content][‘some content] when using javascript. It seems to be different from the general array,
but I don’t know what it means and how to use it.
what is its name?

For exmple

const Data = {
  'apple':{
    'banana':{
      //....
    }
  }
}

I tried googling but I can’t figure it out because I don’t even know how to describe it haha

3

Answers


  1. They are property accessors, its a way to access data in an object literal or JSON using the key, for object literals you can also use the dot operator a an accessor.

    const obj = {
      name: "John Doe",
      age: 25,
    };
    
    console.log(obj.name); // John Doe
    console.log(obj['age']); // 25
    
    Login or Signup to reply.
  2. The main structure is an object. Objects are a list with keys where you can access a specific value with a specific key. You are making an object inside an object inside an object, so Data["apple"] will return {"banana": {/*whatever you have in here*/}}. The [value] is an object assessor.

    Example:

    const values = {
        "one": 1,
        "tree": "banana",
        "otherValues": {
            "seven": 7
        }
    }
    
    console.log(values["one"]) // 1
    console.log(values.one) // 1
    console.log(values.tree) // Banana
    console.log(values["otherValues"] // { "seven": 7 }
    console.log(values.otherValues.seven) // 7
    
    Login or Signup to reply.
  3. The notation jsonData['someKey']['anotherKey'] looks like array access but is actually for accessing nested properties within objects, not array elements. This is object notation, not array notation, used to retrieve values from objects based on keys. Each key in the notation represents a level in the nested object structure.

    Accessing Nested Object Properties

    There are two primary ways to access properties of an object:

    1. Dot Notation: object.property

      • Simpler and more common, but can only be used with property names that are valid JavaScript identifiers (e.g., no spaces, not starting with a digit, etc.).
    2. Bracket Notation: object['property']

      • More versatile because it can be used with any string value, including property names that include spaces, reserved words, or start with digits. Also, it’s the only way to access a property name stored in a variable.

    Here is an example:

    const bananaObject = Data['apple']['banana']; // Using bracket notation
    // or equivalently
    const bananaObject = Data.apple.banana; // Using dot notation, if the property names are valid identifiers
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search