14

I have an associative array in JS.

var array = {
    'one' : 'first',
    'two' : 'second',
    'three' : 'third'
};

How can I add new pair in it

Artur Keyan
  • 7,643
  • 12
  • 52
  • 65
  • 2
    Javascript doesn't have "associative arrays". It has Objects (which are unordered collections of name/value pairs) and Arrays, which are just objects with a special length property and some handy methods that operate on properties with numeric names. Array properties are also unordered, but can be accessed in sequence using a loop (for, while or do). – RobG Aug 04 '11 at 06:11

3 Answers3

29
array['newpair'] = 'new value';

or

array.newpair = 'newvalue';

This is quite a decent read on the subject.

user1122345
  • 396
  • 3
  • 4
5

It's an object literal, not really an "associative array".

Just do array['something'] = 'something';

meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
1

(Maybe a bit late, but very useful for future devs)

Instead of trying to make associative array or creating your own object, I'd suggest https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map It is more handy ;)

// Eg. 1
let wrongMap = new Map()
wrongMap['bla'] = 'blaa'
wrongMap['bla2'] = 'blaaa2'

console.log(wrongMap)  // Map { bla: 'blaa', bla2: 'blaaa2' }

// Eg .2
let contacts = new Map()
contacts.set('Jessie', {phone: "213-555-1234", address: "123 N 1st Ave"})
contacts.has('Jessie') // true
contacts.get('Hilary') // undefined
contacts.set('Hilary', {phone: "617-555-4321", address: "321 S 2nd St"})
contacts.get('Jessie') // {phone: "213-555-1234", address: "123 N 1st Ave"}
contacts.delete('Raymond') // false
contacts.delete('Jessie') // true
console.log(contacts.size) // 1

4givN
  • 2,936
  • 2
  • 22
  • 51