0

I'm new to Javascript and I would like to know how to make an associative array in JavaScript. I want to push my array in the main array to for an associative array. I know how to do it in PHP.

PHP equivalent:

$associativeArray = [
    [
        'name' => 'Bob',
        'age' => '18',
        'address' => '442 Grand Ave'
    ],
];

How can I do the same in Javascript?

Here is my code:

var mainArray = {};

var arr = [];
arr['name'] = 'Bob';
arr['age'] = '18';
arr['address'] = '442 Grand Ave';

arr.push(mainArr);

console.log(mainArr); // output: {}
2
  • JavaScript is not PHP. The Array is a different structure. Commented Feb 5, 2019 at 21:14
  • Use an object literal for the arr variable, and switch your push around to mainArr.push(arr). Commented Feb 5, 2019 at 21:15

2 Answers 2

2

In Javascript, you use {...} to define objects (key-value pairs, roughly equivalent to associative arrays in PHP), and [...] to define arrays. What you're looking for is:

var arr = [];

var obj = {};
obj['name'] = 'Bob';
obj['age'] = '18';
obj['address'] = '442 Grand Ave';

arr.push(obj);

console.log(arr);

Or more succinctly:

var array = [{
  name: 'Bob',
  age: '18',
  address: '442 Grand Ave',
}];

console.log(array); // output: {}

On a further note, JavaScript does allow mixing numeric indexes (e.g. arr[0]) and string keys (e.g. obj['name']) on a single object, but in practice, this is generally discouraged because it can be quite confusing.

Sign up to request clarification or add additional context in comments.

Comments

1

JavaScript is a lot different than PHP. The example you have shown with PHP would not work with JavaScript. I am not sure what exactly you would like to achieve but here's sort of an updated code to what you were trying to do.

var mainArray = {};

var arr = [];
mainArray['name'] = 'Bob';
mainArray['age'] = '18';
mainArray['address'] = '442 Grand Ave';

arr.push(mainArray);

console.log(arr); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.