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.
A:
Alex Fort
2009-01-29 14:41:09
+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
2009-01-29 14:43:47
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
2009-01-29 14:49:39
You would destroy other properties from car
José Leal
2009-01-29 14:50:53
Depends on the usage, but yeah it could cause issues if using instanceof
roryf
2009-01-29 14:51:28
+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
2009-01-29 14:48:10
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
2009-01-29 14:49:02
+1
A:
In javascript there are 2 ways to add a property to an object.
With direct
data.car[0].name = 'jose';
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
2009-01-29 14:49:25