1

I am trying to create something like

var[1] = {object1, object2};
var[2] = {object1, object3);

Or something like that so that I can loop over each result and get all the objects associated with that key. The problem is I am either really tried or something because I can't seem to figure out how to do that.

In PHP I would do something like

$var[$object['id']][] = object1;
$var[$object['id']][] = object2;

How can I do something like that in Javascript?

I have a list of object elements, that have a key value called id and I want to organize them all by ID. Basically...

[0] = { id: 2 },
[1] = { id: 3 },
[2] = { id: 2 },
[3] = { id: 3 }

And I want to have them organized so it is like

[0] = { { id: 2 }, { id: 2 } }
[1] = { { id: 3 }, { id: 3} }
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Steven
  • 13,250
  • 33
  • 95
  • 147

3 Answers3

2
var indexedArray = [];

for(var key in myObjects) {

    var myObject = myObjects[key];

    if(typeof(indexedArray[myObject.id]) === 'undefined') {
        indexedArray[myObject.id] = [myObject];
    }
    else {
        indexedArray[myObject.id].push(myObject);
    }
}

console.log(indexedArray);

http://jsfiddle.net/2fr4k/

FuzzyTree
  • 32,014
  • 3
  • 54
  • 85
  • A couple of things to be careful of with this solution: If `id` is not an integer in the range of 0 to 2^32 - 1 (say for example `-1`) or if `id`s do not run sequentially from `0` then you end up with a sparse array. – Xotic750 May 26 '14 at 12:07
  • Also, be careful when using `for..in` on arrays. http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea – Xotic750 May 27 '14 at 02:34
1

Array is defined by square brackets:

var myArray = [{ "id": 2 }, { "id": 3 }];

What you had is not a valid syntax.

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
0

Using ECMA5 methods, you could do something like this.

Javascript

var d1 = [{
        id: 2
    }, {
        id: 3
    }, {
        id: 2
    }, {
        id: 3
    }],
    d2;


d2 = d1.reduce(function (acc, ele) {
    var id = ele.id;

    if (!acc[id]) {
        acc[id] = [];
    }

    acc[id].push(ele);

    return acc;
}, {});

d2 = Object.keys(d2).map(function (key) {
    return this[key];
}, d2);

console.log(JSON.stringify(d2));

Output

[[{"id":2},{"id":2}],[{"id":3},{"id":3}]] 

On jsFiddle

Xotic750
  • 22,914
  • 8
  • 57
  • 79