medievalmatt medievalmatt - 1 year ago 68
Javascript Question

Building an object in javascript returns error

I am building an array as an object, which a function I'm writing will eventually crawl. It's static data, so once it's populated nothing is likely to be added or removed, but I'm having difficulty formatting it properly.

The variable declaration works great if I have only one record's worth of data:

var panel = {
'x':[1.63, 3.53],
'y':[6.58, 7.26],
'z':[2.05, 2.81]

However, if I try to add a second record's worth of information:

var panel = {'0':['url':'',
'x':[-9.38, -7.47],
'y':[6.80, 7.49],
'z':[-8.18, -8.85]],'1':[
'x':[1.63, 3.53],
'y':[6.58, 7.26],
'z':[2.05, 2.81]}

I get the following error:
SyntaxError: Unexpected token ':'. Expected either a closing ']' or a ',' following an array element.
I've tried every combination I can think of: wrapping each hunk of data in braces or square brackets and both explicitly declaring the keys and not declaring the keys. It all results in variations of this error. Where am I messing up in terms of formatting this information?

Answer Source

Your combining object literals and arrays in a weird way. Here is probably what you are looking for


This is an array of objects, where the objects can be your data records.

What I see in the code that is the problem is

[ '0': '.....'] //illegal

Square brackets represent arrays, which is a list of data whether they are strings, numbers, or objects.

[ '0', {}, 'blah', 1.2] //legal

Curly brace is the object literal or associative arrays.

{ '0': '...' }


People say that arrays are object literals because they behave like one at run-time. You are defining array and object literals, so there are specific rules that come into play. In your code, if you instead wrote

var panel = [];
var index1 = []
panel['0'] = index1
index1['url'] = 'http://';
index1['x'] = 1.2;
var index2 = [];
index2['url'] = 'http://';

This would work, but as you can see it is a little convoluted. When you are writing an array literal, it is a list of comma separated values, and not associated keys. If you want associated keys, use curly brace.

If you want more info, search for JSON data format.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download