JSON stands for JavaScript Object Notation. A JSON object is really a string that has yet to be turned into the object it represents.
To add a property to an existing object in JS you could do the following.
object["property"] = value;
or
object.property = value;
If you provide some extra info like exactly what you need to do in context you might get a more tailored answer.
Answer from Quintin Robinson on Stack OverflowJSON stands for JavaScript Object Notation. A JSON object is really a string that has yet to be turned into the object it represents.
To add a property to an existing object in JS you could do the following.
object["property"] = value;
or
object.property = value;
If you provide some extra info like exactly what you need to do in context you might get a more tailored answer.
var jsonObj = {
members:
{
host: "hostName",
viewers:
{
user1: "value1",
user2: "value2",
user3: "value3"
}
}
}
for(var i=4; i<=8; i++){
var newUser = "user" + i;
var newValue = "value" + i;
jsonObj.members.viewers[newUser] = newValue ;
}
console.log(jsonObj);
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");
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.
I'll give you an example from your add function:
function add(time, user, text){
// this line is all I changed
var message = {'time' : time, 'user' : user, 'text' : text};
if (msg.length >= 50)
msg.shift();
msg.push(message);
}
As you can see the message variable is no longer an array but it's the Object you want it to be.
From this you should be able to work out how to create a new array and add the values you want to it.
Try this:
var len = msg.length;
var obj = [];
for (var i = 0; i < len; i++) {
var item = {
'time': msg[i][0],
'user': msg[i][1],
'text': msg[i][2]
}
obj.push(item);
}
Could you do the following:
obj = {
"1":"aa",
"2":"bb"
};
var newNum = "3";
var newVal = "cc";
obj[newNum] = newVal;
alert(obj["3"]); // this would alert 'cc'
You can use dot notation or bracket notation ...
var obj = {};
obj = {
"1": "aa",
"2": "bb"
};
obj.another = "valuehere";
obj["3"] = "cc";