You have to use bracket notation:

var obj = {};
obj[a[i]] = 0;
x.push(obj);

The result will be:

x = [{left: 0}, {top: 0}];

Maybe instead of an array of objects, you just want one object with two properties:

var x = {};

and

x[a[i]] = 0;

This will result in x = {left: 0, top: 0}.

Answer from Felix Kling on Stack Overflow
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ javascript โ€บ javascript array push key value
How to Push Key-Value Pair Into an Array Using JavaScript | Delft Stack
February 2, 2024 - We utilized the push() method to add the obj object to the arr array. This action effectively inserted the object into the array as a single element. Finally, we logged the arr array to the console, presenting an array that held a single object with all the desired key-value pairs. JavaScript offers multiple ways to incorporate key-value pairs into arrays, each catering to distinct programming needs and preferences.
๐ŸŒ
Talkerscode
talkerscode.com โ€บ howto โ€บ javascript-array-push-key-value-pair.php
JavaScript Array Push Key Value Pair
In this method, we are going to use for loop to get the key-value pair. <!DOCTYPE html> <html lang = " en " > <head> <meta charset = " UTF - 8" > <meta http-equiv = " X-UA-Compatible " content = " IE=edge " > <meta name = " viewport " content = " width = device-width , initial-scale = 1.0 " > <title> JavaScript array push key value pair </title> <style> body { font-family : 'Lucida Sans', Verdana , sans-serif ; } h1 { font-size : larger ; font-weight : bolder ; color : rgb(113, 221, 113) ; text-align : center ; } h3 { text-align : center ; } </style> </head> <body> <h1> TALKERSCODE </h1> <h3> JavaScript array push key value pair </h3> <script> var array1 = [ "key1" , "key2" ,"key3" , "key4" ,"key5" ] ; var array2 = [ 1 , 3 , 5 , 7 , 9 ] ; var result = { } ; for ( var i = 0 ; i <array1.length ; i++ ) { result[ array1 [ i ] ] = array2 [ i ] ; } console.log ( result ) ; </body> </html>
๐ŸŒ
EyeHunts
tutorial.eyehunts.com โ€บ home โ€บ javascript array push key value | example code
JavaScript array push key value | Example code
August 20, 2022 - 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).
Top answer
1 of 5
225

There are no keys in JavaScript arrays. Use objects for that purpose.

var obj = {};

$.getJSON("displayjson.php",function (data) {
    $.each(data.news, function (i, news) {
        obj[news.title] = news.link;
    });                      
});

// later:
$.each(obj, function (index, value) {
    alert( index + ' : ' + value );
});

In JavaScript, objects fulfill the role of associative arrays. Be aware that objects do not have a defined "sort order" when iterating them (see below).

However, In your case it is not really clear to me why you transfer data from the original object (data.news) at all. Why do you not simply pass a reference to that object around?


You can combine objects and arrays to achieve predictable iteration and key/value behavior:

var arr = [];

$.getJSON("displayjson.php",function (data) {
    $.each(data.news, function (i, news) {
        arr.push({
            title: news.title, 
            link:  news.link
        });
    });                      
});

// later:
$.each(arr, function (index, value) {
    alert( value.title + ' : ' + value.link );
});
2 of 5
60

This code

var title = news.title;
var link = news.link;
arr.push({title : link});

is not doing what you think it does. What gets pushed is a new object with a single member named "title" and with link as the value ... the actual title value is not used. To save an object with two fields you have to do something like

arr.push({title:title, link:link});

or with recent Javascript advances you can use the shortcut

arr.push({title, link}); // Note: comma "," and not colon ":"

If instead you want the key of the object to be the content of the variable title you can use

arr.push({[title]: link}); // Note that title has been wrapped in brackets
๐ŸŒ
QoDesign
blog.qodesign.net โ€บ push-associative-array-into-array-in-javascript
Push associative array into array in JavaScript - QoDesign
March 27, 2023 - We then use square bracket notation to set a property on obj with the name specified by the key parameter and the value specified by the value parameter. For example, when we call insert("name", "John"), it sets the property name on obj with ...
Find elsewhere
๐ŸŒ
YouTube
youtube.com โ€บ watch
javascript array push key value pair dynamically - YouTube
Get Free GPT4o with 1 million code snippet from https://codegive.com sure! in javascript, you can dynamically add key-value pairs to an array using the `pus...
Published: June 15, 2024
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ Array โ€บ push
Array.prototype.push() - JavaScript - MDN Web Docs
July 12, 2026 - Notice that the elements are wrapped in an extra array โ€” otherwise, if the element is an array itself, it would be spread instead of pushed as a single element due to the behavior of concat(). The push() method is generic. It only expects the this value to have a length property and integer-keyed ...
๐ŸŒ
YouTube
youtube.com โ€บ hey delphi
Array : JavaScript Array Push key value - YouTube
Array : JavaScript Array Push key valueTo Access My Live Chat Page, On Google, Search for "hows tech developer connect"I promised to share a hidden feature w...
Published: May 26, 2023
Views: 9
๐ŸŒ
Talkerscode
talkerscode.com โ€บ howto โ€บ javascript-push-object-into-array-with-key.php
JavaScript Push Object Into Array With Key
We can use bracket notation to assign one or more key-value pairs to the object, and then use the push method to add the object to the end of the Array once the values have been assigned.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ javascript โ€บ how-to-store-a-key-value-array-in-javascript
How to store a key=&gt; value array in JavaScript ? - GeeksforGeeks
July 12, 2025 - Using the Objects approach in JavaScript, key-value pairs are stored in an object where each key is associated with a specific value. Objects are ideal for mapping keys to values and are versatile, handling various data types including numbers, strings, and other objects. ... for (let i = 0; i < keys.length; i++) { // obj = Object // keys = key array // values = value array obj[keys[i]] = values[i]; }
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ how-to-store-a-key-value-array-in-javascript
How to store a key=> value array in JavaScript ? | GeeksforGeeks
January 10, 2025 - Using JavaScript for each loopIn this method, traverse the entire associative array using a for each loop and display the key elements of the array. javascriptlet a = {Newton: "Gravity",Albert: "Energy",Edison: "B ... To get a key in a JavaScript object by its value means finding the key associated with a specific value in an object.