Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Adding to an associative array

I have a function called insert which takes two parameters (name and telnumber).

When I call this function I want to add to an associative array.

So for example, when I do the following:

insert("John", "999");
insert("Adam", "5433");

I want to it so be stored like this:

[0]
{
name: John, number: 999
}
[1]
{
name: Adam, number: 5433
}
like image 455
ritch Avatar asked Nov 30 '11 15:11

ritch


People also ask

How do I add an element to an associative array?

Use the array_merge() Function to Add Elements at the Beginning of an Associative Array in PHP. To add elements at the beginning of an associative, we can use the array union of the array_merge() function.

Does JavaScript support associative array?

JavaScript does not support associative arrays. You should use objects when you want the element names to be strings (text). You should use arrays when you want the element names to be numbers.

Can you append to an array in JavaScript?

Sometimes you need to append one or more new values at the end of an array. In this situation the push() method is what you need. This method accepts an unlimited number of arguments, and you can add as many elements as you want at the end of the array.

What is associative array in JavaScript with example?

An associative array is declared or dynamically createdWe can create it by assigning a literal to a variable. var arr = { "one": 1, "two": 2, "three": 3 }; Unlike simple arrays, we use curly braces instead of square brackets. This has implicitly created a variable of type Object.


2 Answers

Something like this should do the trick:

var arr = [];
function insert(name, number) {
    arr.push({
        name: name,
        number: number
    });        
}
like image 59
jabclab Avatar answered Oct 03 '22 20:10

jabclab


I would use something like this;

var contacts = [];
var addContact = function(name, phone) {
    contacts.push({ name: name, phone: phone });
};

// Usage
addContact('John', '999');
addContact('Adam', '5433');

I don’t think you should try to parse the phone number as an integer as it could contain white-spaces, plus signs (+) and maybe even start with a zero (0).

like image 32
Stefan Avatar answered Oct 03 '22 19:10

Stefan