Associative Array Versus Object in JavaScript

Associative array versus object in JavaScript

In JavaScript, objects are associative arrays...there aren't separate concepts for them. You are also able to safely use '.' in a key name, but you can only access the value using the bracket notation:

var foo = {}
foo['bar'] = 'test';
foo['baz.bin'] = 'value';

alert(foo.bar); // Shows 'test'
alert(foo['baz.bin']); // Shows 'value'

If you're using them already and they work, you're safe.

What's the difference between objects and associated array in javascript?

Not really, here's why:

var arr = new Array();
arr["foo"] = 100;
arr["bar"] = 200;
console.log(arr.length); // Prints 0.

Adding elements to an associative array should increase its length (IMO).

It looks and acts (somewhat) like an associative array because of syntactic sugar. What appear to be "array entries", however, are (just) object properties.

difference between Associative Arrays and Objects in JS

The main difference is that an associative array doesn't exist in JS and objects do

Is JavaScript Object nothing but an associative array?

No, objects are more than that.

Object is indeed a map/dictionary, but additionally every object inherits some of the properties (key-value pairs) from another object. That other object is called prototype.

For example:

var o = {
x: 1
};

console.log(o.x === undefined); // false, obviously
console.log(o.toString === undefined); // false, inherited from prototype

Most commonly a prototype is set by creating an object with a constructor function:

var d = new Date();
console.log(d.hasOwnProperty('getYear')); // false, it's inherited

EDIT:

Here's how the prototype works using constructor functions (it's one of the ways to do OOP in JS):

// constructor function
// starts with capital letter, should be called with new
var Person = function (name, age) {
// set properties of an instance
this.name = name;
this.age = age;
};

// functions to be inherited are in the prototype
Person.prototype.sayHello = function () {
return this.name + ' is ' + this.age + ' old';
};

// new:
// - creates the object
// - sets up inheritance from prototype
// - sets the object as the context of the constructor function call (this)
var p = new Person('Jason', 27);

console.log(p.sayHello());

Diffrence between [] and {} for Associative array in Javascript

The both DB1 and DB2 behaves as expected exactly in the same way, at least it appears so to me.

Not quite. [] creates an array, {} creates an object. In JavaScript, standard arrays aren't really arrays at all, they're just objects with some special behavior. You can add properties to those objects that aren't array entries, just like you can any other object. In your example, you're not using the array as an array, so both work, but if you were using the array as an array (using array indexes, length, push, splice, etc.), only the [] version would work as only that gives you an array.

Use an array when you need the features of an array. Use an object when you just need to map names to values. If using an array, be sure to use genuine array indexes, not non-index property names like '001'. (Details on that below.)

Here's an example of how you're not using the array as an array:

DB1.user['001'] = ...;

That does not create an array entry. Proof:

var a = [];
a['001'] = "foo";
console.log(a.length); // 0

It creates a property on the object with the name "001", but that property is not an array entry. In contrast:

a[1] = "foo";

or

a['1'] = "foo";

...creates an array entry:

var a = [];
a[1] = "foo";
console.log(a.length); // 2 (see below)

Why the difference? Again, standard arrays are just objects with special behavior. One of the key bits of special behavior relates to a certain class of property names, specifically those that are all digits in normal numeric form (no leading zeros) (they're still strings, even though we act like they're numbers). A property with a name in standard numeric form (and within range, they're allowed to be 0 through 232-2, inclusive) is an array entry.


I keep saying "standard arrays" because JavaScript is getting typed arrays (in fact, they're already in most engines):

var a = new Int32Array(10);

Typed arrays are actual arrays, completely unlike the [] "arrays".


Side note: Why was the length 2 here?

var a = [];
a[1] = "foo";
console.log(a.length); // 2

Because JavaScript arrays, by their nature, are sparse, and one of the special behaviors I was talking about is that when you add a property to an array that fits the definition of an array entry, length is set to the value one greater than the highest-numbered array entry. So even though our a array has only one entry, its length is 2.


Further side note: Objects are not called "associative arrays" in JavaScript, that's primarily a PHP term for a very special data structure it has which is an ordered name/value map. In JavaScript, we call them "objects" (primarily), or sometimes "maps" or "dictionaries." They are unordered, unlike PHP's associative arrays.


More importantly, in this case, if it's not only the expression, how different and which one is more efficient, that's what I would like to know.

Since you're not using the array as an array, I'd expect the object version to be slightly more efficient, because engines will initially try to optimize based on your using an array as an array, and then fall back to the object behavior when you do things like your '001' property name. So probably use an object from the start.

But in general, JavaScript "efficiency" is a very difficult topic. What's efficient on one engine is not efficient on other engines. Even if you don't believe premature optimization is a waste of time in other realms, it really is with JavaScript. Obviously don't do dumb things, but in general, wait until a performance problem arises and then tackle that problem on the platform on which it arises (and then test the other platforms you support to make sure you haven't introduced a new problem there).

Javascript array with associative array difference

Easy and simple way to achieve your goal

var a1 = [{"a":"A"},{"b":"B"}];
var a2 = [{"a":"A"},{"c":"C"},{"b":"B"}];

var max = (a1.length > a2.length) ? a1 : a2;
var min = (a1.length > a2.length) ? a2 : a1;
var newArray = [];

for ( var i = 0; i < max.length; i++ ) { // saving elements into string
max[i] = JSON.stringify(max[i]);
if ( typeof min[i] !== undefined ) {
min[i] = JSON.stringify(min[i]);
}
}

for ( var i = 0; i < max.length; i++ ) { // checking values uniqueness
if ( min.indexOf(max[i]) === -1 ) {
newArray.push(max[i]);
}
}

// if you need new Array's elements back in object do following iteration
for ( var i in newArray ) { // loop recreate results array's elements into object again
newArray[i] = JSON.parse(newArray[i]);
}

console.log(newArray); // result : [Object { c="C"}]

JSFiddle

Creating some associative array in JavaScript

JavaScript doesn't have "associative arrays".

It has objects, which you can store values on in named properties.

It has arrays, which store an ordered set of values via integer properties. Since they are a type of object, you can also store named values on them (but you can't create them using the literal syntax, only add them after the array is created) but this isn't considered good practise and they will be ignored by just about anything that has special case handling for arrays.

As of ES6 it also has Maps which are similar to objects in that you can give them named values, but also to arrays in that order is preserved. There is no literal syntax for creating a Map.



Related Topics



Leave a reply



Submit