EN
JavaScript - push to array
1 answers
3 points
How can I push new values to the following array?
xxxxxxxxxx
1
var json = { "foo": "a", "bar": "b" };
I've tried:
xxxxxxxxxx
1
json.push("hello": "world");
But it doesn't work.
1 answer
3 points
This is not an array.
It's an object and what you are trying to do is to add a key/value pair to the object.
You can do it in two ways:
xxxxxxxxxx
1
var object = { 'foo': 'a', 'bar': 'b' };
2
3
object.hello = 'world'; // adds key/value pair using dot notation
4
5
console.log(JSON.stringify(object)); // {"foo":"a","bar":"b","hello":"world"}
or:
xxxxxxxxxx
1
var object = { 'foo': 'a', 'bar': 'b' };
2
3
object['hello'] = 'world'; // adds key/value pair using array notation
4
5
console.log(JSON.stringify(object)); // {"foo":"a","bar":"b","hello":"world"}
You can also do it as an array but it requires a different syntax:
xxxxxxxxxx
1
var array = [{ 'foo': 'a' }, { 'bar': 'b' }];
2
3
array.push({ 'hello': 'world' });
4
5
console.log(JSON.stringify(array)); // [{"foo":"a"},{"bar":"b"},{"hello":"world"}]
References
0 commentsShow commentsAdd comment