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.

You can use an object as a key-value store, where the keys are strings (or symbols) and the values can be of any type, including arrays. Here’s an example of pushing values into an array stored in an object:

// Create an object
const myObject = {};

// Initialize an array as a value
myObject['myArray'] = [];

// Push values into the array
myObject['myArray'].push('value1');
myObject['myArray'].push('value2');

console.log(myObject['myArray']); // Output: ['value1', 'value2']

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

Using Maps: Maps are a built-in data structure in JavaScript that allows you to associate values with keys. Unlike objects, Map keys can be of any type. Here’s an example of using a Map to push values into an array:

// Create a new Map
const myMap = new Map();

// Initialize an array as a value
myMap.set('myArray', []);

// Push values into the array
myMap.get('myArray').push('value1');
myMap.get('myArray').push('value2');

console.log(myMap.get('myArray')); // Output: ['value1', 'value2']

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

Discover more from Tutorial

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

Continue reading