Skip to content

JavaScript associative array push | Example code

  • by

Just use the Array push() method to push values in JavaScript associative array.

car.push({type: value1, age: value2})

If you want named properties, don’t use an Array. Arrays are for ordered data structures accessed by index.

Use an Object instead.

var obj = {};
obj['12345'] = "someName";

JavaScript associative array push

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>

    var car = [];
    car [0] = {type: "Audi", age: "10"};
    car [1] = {type: "BMW", age: "6"};
    car [2] = {type: "Tesla", age: "2"};

    value1 = "Hyundai"
    value2 = "14";

    car.push({type: value1, age: value2});

    console.log(car);

  </script>
</body>
</html> 

Output:

JavaScript associative array push

Array push in JavasSript associative Array

var markedDates = [];
var markedDate = {};
    markedDate['dates'] = [];
    markedDate['dates'].push({day: 1, month: 12, year: 2021});
    markedDate['dates'].push({day: 15, month: 12, year: 2021});
    markedDate['styleClass'] = 'test';
    markedDates.push(markedDate);

console.log(markedDates);

Output:

[
  {
    "dates": [
      {
        "day": 1,
        "month": 12,
        "year": 2021
      },
      {
        "day": 15,
        "month": 12,
        "year": 2021
      }
    ],
    "styleClass": "test"
  }
]

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

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.