17

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
}
3
  • 5
    "associative arrays" are just objects in JavaScript. Commented Nov 30, 2011 at 15:36
  • 2
    Technically, you mean you want to add objects to an array which is numerically indexed. JavaScript doesn't have "associative" arrays. Commented Nov 30, 2011 at 15:36
  • Please show your existing function definition, and how you have defined the array it adds to Commented Nov 30, 2011 at 15:37

7 Answers 7

37

Something like this should do the trick:

var arr = [];
function insert(name, number) {
    arr.push({
        name: name,
        number: number
    });        
}
Sign up to request clarification or add additional context in comments.

1 Comment

You might point out that OP is not using an associative array; he's using an array of objects.
5

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).

2 Comments

Good point about the parseInt, I just saw "Number"- didn't think about the context :-)
Just spotted, the contacts var above should be [] not {}.
4
var users = [];

users.push({name: "John", number: "999"});
users.push({name: "Adam", number: "5433"});

Comments

2

If you want you can add your function to Array.prototype.

Array.prototype.insert = function( key, val ) {
    var obj = {};
    obj[ key ] = val;
    this.push( obj );
    return this;
};

And use it like this.

var my_array = [].insert("John", "999")
                 .insert("Adam", "5433")
                 .insert("yowza", "1");

[
   0: {"John":"999"},
   1: {"Adam":"5433"},
   2: {"yowza":"1"}
]

Comments

1

I will assume you're using some array reference with insert:

var arr;
function insert(na, nu) {
  nu = Number(nu) || 0;
  //alternatively
  nu = parseInt(nu, 10);
  arr.push({ name: na, number: nu });
}
arr = [];


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

Comments

0

You can also just assign them directly they don't need to be inserted first

    var form = document.getElementById('ourinput').elements;
    var out={};
    for(var i=0;i<form.length;i++)
    {
        var row=form[i];
        if(row.checked){out[row.id]=row.value;}
    }

the html part

    <form id="ourinput" onsubmit="return false;">
<table>
<tr>
<td><input type="checkbox" id="q1" value="A1"><label for="q1">A1</label></td>
<td><input type="checkbox" id="q2" value="A2"><label for="q2">A2</label></td>
<td><input type="checkbox" id="q3" value="A3"><label for="q3">A3</label></td>
</tr>

      <tr><td><button onclick="test()">Submit</button></td></tr>
<table>
</form>

in my case the form is just a bunch of checkboxes and this is the part that makes an associative array with the id's as the keys for each checkbox that has been checked.

Comments

-2

There is no such term as an "associative array" in JavaScript, though you can use following:

var list = [];

function insert(name, number) {
  list.push({
    name: name,
    number: number
  });
}

5 Comments

"objects as associative arrays" doesn't mean that JS has "associative arrays". everything is an object in JS and you can add properties to anything but it doesn't make these objects associative arrays. btw who downvoted my answer? :)))))))))) it's funny :D
Technically any turning complete language can implement anything any other turing complete language. Thus all computer languages have associative arrays (minus ones like SQL). Also in JS, objects are implemented using lists of name/attribute pairs -- this is possible in JS and not other OO languages like Java since JS treats functions as first class citizens, so in fact they are "associative arrays as objects" not the other way around. and javascript does have them.
love all these comments... do you guys write these comments with serious faces? :)))) thumbs up to down voters. did you try to find "associative array" definition in EcmaScript document?
The problem is that assciative array is not a 'thing' it is a particular behavior of an array. Javascript has arrays that can be addresses associativly. How javascript choses to implement that or what it chosew to call it is javascript's choice but java script still has it. Saying javascript doesnt have associative arrays is like saying perl doesnt have functions because it uses 'subroutines'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.