unfollow
unfollow

Reputation: 225

Shuffle object array while preserving keys

i'm working on a project in which i need to shuffle an object array on DOM ready while also preserving keys.

Example:

     var o = [
    {"key_1": {
        "bruce wayne": "batman"
    }},
    {"key_2": {
        "peter parker": "spiderman"
    }},

    {"key_3": {
        "bruce banner": "hulk"
    }}
];

After:

var o = [
    {"key_3": {
        "bruce banner": "hulk"
    }},
    {"key_1": {
        "bruce wayne": "batman"
    }},

    {"key_2": {
        "peter parker": "spiderman"

    }}
];

i've tried doing this a few different ways but haven't been successful. at this point i'm also not sure if this is the best approach for this.

Additional Info: the application has to iterate through the array, showing one key set at a time.

-appreciate any direction,

Upvotes: 1

Views: 3887

Answers (3)

Oriol
Oriol

Reputation: 288600

Your arrays have syntax errors. It seems you want objects instead of arrays or, since objects have no order, array of objects:

var o = [
    {
        "key_1": {"bruce wayne": "batman"}
    },
    {
        "key_2": {"peter parker": "spiderman"}
    },
    {
        "key_3": {"bruce banner": "hulk"}
    }
];
shuffle(o);

Where shuffle is the function defined in this answer or in this one.

Now your array will be something like

[
    {
        "key_3": {"bruce banner": "hulk"}
    },
    {
        "key_2": {"peter parker": "spiderman"}
    },
    {
        "key_1": {"bruce wayne": "batman"}
    }
];

Upvotes: 0

Bergi
Bergi

Reputation: 665276

You will need an actual array (instead of an syntax error):

var o = [
    {
        "key": 1,
        "bruce wayne": "batman"
    },
    {
        "key": 2,
        "peter parker": "spiderman"
    },
    {
        "key": 3,
        "bruce banner": "hulk"
    }
]

You can shuffle that easily and the keys are preserved.

Upvotes: 0

Raul Guiu
Raul Guiu

Reputation: 2404

First fix o, it was not correct:

var o = [
    {"key_1": {
        "bruce wayne": "batman"
    }},
    {"key_2": {
        "peter parker": "spiderman"
    }},

    {"key_3": {
        "bruce banner": "hulk"
    }}
];

Now using the shuffle from this answer:

function shuffle(o){ 
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};

You call it like this:

o = shuffle(o);

Upvotes: 1

Related Questions