-2

Why do I have an expected token for my json data https://jsfiddle.net/4baLzL4f/

    var myArray = [
        "Key1": {
                "field1": "4",
                "field2": "6.62"
            }   
    ,

        "Key2": {
                "field1": "10",
                "field2": "7.62"
            }
];

Update : What I need is to easily access by key with something like myArray["Key1"]

1
  • invalid array is why Commented Jan 31, 2016 at 14:25

3 Answers 3

3

You may use an object, not an array:

var myObject = {
    "Key1": {
        "field1": "4",
        "field2": "6.62"
    },
    "Key2": {
        "field1": "10",
        "field2": "7.62"
    }
};

document.write(myObject['Key2']['field2'] + '<br>'); // the same 
document.write(myObject.Key2.field2);                // as this
document.write('<pre>' + JSON.stringify(myObject, 0, 4) + '</pre>');

Sign up to request clarification or add additional context in comments.

1 Comment

What I need is to easily access by key with something like myArray["Key1"]
1

If you really want to keep your data structure as a List of objects:

[
  {
    "Key1": {
      "field1": "4",
      "field2": "6.62"
    }
  },
  {
    "Key2": {
      "field1": "10",
      "field2": "7.62"
    }
  }
]

As a Map of objects:

{
  "Key1": {
    "field1": "4",
    "field2": "6.62"
  },
  "Key2": {
    "field1": "10",
    "field2": "7.62"
  }
}

2 Comments

What I need is to easily access by key with something like myArray["Key1"]
I suggest you go with a map of objects.
1

If you want to use an array of objects make it like the following.

var myArray = [
        {
            "Key1": {
                "field1": "4",
                "field2": "6.62"
            }
        },   
        {
            "Key2": {
                "field1": "10",
                "field2": "7.62"
            }
        }
];

If you want to access it directly with keys use it as an object (Key/Value pair)

var myObj = {
            "Key1": {
                "field1": "4",
                "field2": "6.62"
            },
            "Key2": {
                "field1": "10",
                "field2": "7.62"
            }
        }

You can loop through it using for..in loop:

for (var key in myObj) {
  console.log(myObj[key]);
}

1 Comment

What I need is to easily access by key with something like myArray["Key1"]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.