nicholaswmin
nicholaswmin

Reputation: 22989

Shuffle only selected items in an associative array

I have this array right here

I would like to shuffly only answerA, answerB, answerC and answerD fields for each object. So I get back an array where answerA might be answerB, answerC might be answerD etc etc.

What is a simple way to do this?

Upvotes: 0

Views: 134

Answers (1)

georg
georg

Reputation: 215029

Using shuffleArray from https://stackoverflow.com/a/12646864/989121:

   myKeys = ['answerA','answerB','answerC','answerD']
   myValues = myKeys.map(function(k) { return myObject[k] })
   myValues = shuffleArray(myValues)
   myKeys.forEach(function(k) { myObject[k] = myValues.shift() })

That said, a simpler option would be to structure your object like this:

ID: 22
answers: [
    "first", "second answer", etc
],
category: ...
etc

Serially named variables is always an indicator that you actually need an array.

Upvotes: 2

Related Questions