1

I have an array of arrays with data like:

[[0,1],[0,2],[0,3],[1,1]]

What I want is an object that looks like: {0: [1,2,3], 1: [1]}

I tried:

                var obj = {};

                $.each(List, function(index, value) {
                        obj[value[0]] = value[2];

                    });

But it obviously overwrites the previous value for the key. Is there an easy way to add all the values to each unique key (sort of like a dictionary)?

1 Answer 1

3

This tests to see if the property exists. If not, it creates it and assigns the Array.

Once the property and array exist, it can push in the value.

var obj = {};

$.each(List, function(index, value) {
    if( !obj[value[0]] )
        obj[value[0]] = [];

    obj[value[0]].push(value[1]);
});

http://jsfiddle.net/dYz8w/


You can avoid a .push() call when the Array is created if you do this...

var obj = {};

$.each(List, function(index, value) {
    if( !obj[value[0]] )
        obj[value[0]] = [value[1]];
    else
        obj[value[0]].push(value[1]);
});

http://jsfiddle.net/dYz8w/1/


And keep in mind that if you need to guarantee order of iteration, you should use an Array instead of an Object.

var arr = [];

$.each(List, function(index, value) {
    if( !arr[value[0]] )
        arr[value[0]] = [value[1]];
    else
        arr[value[0]].push(value[1]);
});

http://jsfiddle.net/dYz8w/3/

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

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.