[javascript] JavaScript push to array

How do I push new values to the following array?

json = {"cool":"34.33","alsocool":"45454"}

I tried json.push("coolness":"34.33");, but it didn't work.

This question is related to javascript arrays json multidimensional-array

The answer is


Use the push() function to append to an array:

// initialize array
var arr = [
    "Hi",
    "Hello",
    "Bonjour"
];

// append new value to the array
arr.push("Hola");

Now array is

var arr = [
    "Hi",
    "Hello",
    "Bonjour"
    "Hola"
];

// append multiple values to the array
arr.push("Salut", "Hey");

Now array is

var arr = [
    "Hi",
    "Hello",
    "Bonjour"
    "Hola"
    "Salut"
    "Hey"
];

// display all values
for (var i = 0; i < arr.length; i++) {
    console.log(arr[i]);
}

Will print:

Hi
Hello
Bonjour
Hola 
Salut
Hey

Update

If you want to add the items of one array to another array, you can use Array.concat:

var arr = [
    "apple",
    "banana",
    "cherry"
];

arr = arr.concat([
    "dragonfruit",
    "elderberry",
    "fig"
]);

console.log(arr);

Will print

["apple", "banana", "cherry", "dragonfruit", "elderberry", "fig"]

That is an object, not an array. So you would do:

var json = { cool: 34.33, alsocool: 45454 };
json.supercool = 3.14159;
console.dir(json);

var array = new Array(); // or the shortcut: = []
array.push ( {"cool":"34.33","also cool":"45454"} );
array.push (  {"cool":"34.39","also cool":"45459"} );

Your variable is a javascript object {} not an array [].

You could do:

var o = {}; // or the longer form: = new Object()
o.SomeNewProperty = "something";
o["SomeNewProperty"] = "something";

and

var o = { SomeNewProperty: "something" };
var o2 = { "SomeNewProperty": "something" };

Later, you add those objects to your array: array.push (o, o2);

Also JSON is simply a string representation of a javascript object, thus:

var json = '{"cool":"34.33","alsocool":"45454"}'; // is JSON
var o = JSON.parse(json); // is a javascript object
json = JSON.stringify(o); // is JSON again

object["property"] = value;

or

object.property = value;

Object and Array in JavaScript are different in terms of usage. Its best if you understand them:

Object vs Array: JavaScript


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to multidimensional-array

what does numpy ndarray shape do? len() of a numpy array in python What is the purpose of meshgrid in Python / NumPy? Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray Typescript - multidimensional array initialization How to get every first element in 2 dimensional list How does numpy.newaxis work and when to use it? How to count the occurrence of certain item in an ndarray? Iterate through 2 dimensional array Selecting specific rows and columns from NumPy array