0

Okay, I have taken a tutorial to create an unnamed object in an array using a function Given an array called contacts in which two named objects exist:

function add(firstName, lastName, phoneNumber, email) {

contacts[contacts.length] = {
    firstName: firstName,
    lastName: lastName,
    phoneNumber: phoneNumber,
    email: email
    };
}

add("Buddy", "King", "312-555-5555", "[email protected]");

that adds the unnamed object. But what do I do if I want to give the new object a name? I would like to use the first parameter )"Buddy" as the object name, so convert the string to ???

3
  • 1
    Give the object a name? It's a little unclear what you're asking. Could you post an example of a "named" object? Commented Jul 22, 2014 at 20:46
  • Are you trying to change an already existing entry? And find the entry by searching by first name? Commented Jul 22, 2014 at 20:47
  • 1
    Read about javascript arrays. It will help you in the long run. Commented Jul 22, 2014 at 20:54

1 Answer 1

2

Use this (associative array):

contacts[firstName] = {
    firstName: firstName,
    lastName: lastName,
    phoneNumber: phoneNumber,
    email: email
};

Now you can get the "Buddy" entry with contacts['Buddy']. Note that all arrays in JS are associative but numbered arrays don't look much like it.

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

4 Comments

Not to be too literal, but there's no such thing as associative arrays. There are Arrays and there are Objects. Arrays are Objects. Objects have properties. There's almost never a good reason to set properties (that aren't numeric) on Arrays. Arrays are meant to be used with numeric indexes and the specific methods provided (push, pop, etc.) that manipulate the internal representation of data (reflected in the length property). I think your solution is ideal, but contacts should be an object literal ({}), not an array ([])
@Ian: Thank you for pointing this out. I didn't want to go into details about objects, objects with array behaviour and apparent arrays that lack array behaviour (such as arguments) and further intrinsics you can look up in Crockford's Good parts. And of course, contacts = {};. The difference is here that JS has only associativity (from an arbitrary key to an object) and never has an actual index (or address offset, such as in C and C++). In that sense, all objects use associativity and therefore arrays do too. But that's already too long for a comment :)
Thanks, finally getting comfortable with JS language, so now I know what you meant!
I'm guessing that what I ought to be doing is creating a prototype, then making a new instance of the prototype (the Buddy object).

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.