views:

138

answers:

5
A: 

You should be able to use the syntax that you posted. Javascript lets you add properties to an object just by assignment. Since the JSON string is just parsed as a normal object, you can just specify a new property and assign the values you want.

Alex Fort
+1  A: 

Using your example above, something like:

data.car[0] = { name: "civic" };
data.car[1] = { name: "s2000" };

This will assign a new object to the array element, with one property 'name'. Alertnatively, for a bit more code re-use:

function car( name) {
    this.name = name
}
data.car[0] = new car("civic");
data.car[1] = new car("s2000");
roryf
It would mean though that the members of the array would have different constructors, that may be useful, OTH it could cause a problem.
AnthonyWJones
You would destroy other properties from car
José Leal
Depends on the usage, but yeah it could cause issues if using instanceof
roryf
+1  A: 

This will add a new car to the array:-

data.car.push({name: "Zafira"});

BTW, you want to be careful with using eval to parse JSON, it could lead you code open to an injection attack.

AnthonyWJones
A: 

Assuiming you have an input box you could attach a blur event (or whenever you want the car added)

function addCar(carname){
    data.car.push({name:carname})
}
kouPhax
+1  A: 

In javascript there are 2 ways to add a property to an object.

  1. With direct

    data.car[0].name = 'jose';

  2. Acessing just like a array:

    data.car[0]['name'] = 'jose';

So if you have one field to a name and one for the value you can create then just like:

<input type="text" id="name" />
<input type="text" id="value" />
<script type="text/javascript">
    var d = function(id) {
        return document.getElementById(id);
    }
    data.car[0][d("name").value] = d("value").value
</script>
José Leal