Skip to content

JavaScript array push key value | Example code

  • by

You have to use bracket notation to push a key value into a JavaScript array.

obj["key3"] = "c"; // dynamic - 'key3' can be a variable

Note: use .push() method doesn’t work on an object.

JavaScript array push key value

Simple example code push key and value into an array in JS.

<!DOCTYPE html>
<html>
<body>
  <script >
    var items = [{
      'id1': 1,
      'id2': 2,
      'id3': 3,
      'id4': 4
    }];

    items[0].id5= 5;
    console.log(items)
  </script>
</body>
</html>

Output:

JavaScript array push key value

How to add a new object (key-value pair) to an array in JavaScript?

Answer: Use push() to add elements to the end of an array.

items.push({'id':5});

Use unshift() if need to add some element to the beginning of the array i.e:

items.unshift({'id':5});

Demo:

items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];
items.unshift({'id': 0});
console.log(items);

And use splice() in case you want to add an object at a particular index i.e:

items.splice(2, 0, {'id':5});
           // ^ Given object will be placed at index 2...

Demo:

items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];
items.splice(2, 0, {'id': 2.5});
console.log(items);

Sometimes .concat() is better than .push() since .concat() returns the new array whereas .push() returns the length of the array.

Therefore, if you are setting a variable equal to the result, use .concat().

items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];
newArray = items.push({'id':5})

In this case, newArray will return 5 (the length of the array).

newArray = items.concat({'id': 5})

Do comment if you have any doubts or suggestions on this Js array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading