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} }

3 Answers 3

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/

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

2 Comments

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 ids do not run sequentially from 0 then you end up with a sparse array.
Also, be careful when using for..in on arrays. stackoverflow.com/questions/500504/…
1

Array is defined by square brackets:

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

What you had is not a valid syntax.

Comments

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

Comments

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.