javascript 如何 Shuffle JSON.parse数据?[duplicate]

hi3rlvi2  于 2023-02-18  发布在  Java
关注(0)|答案(3)|浏览(144)
    • 此问题在此处已有答案**:

How to randomize (shuffle) a JavaScript array?(69个答案)
How can I shuffle an array? [duplicate](2个答案)
昨天关门了。
有可能从ajax中打乱json解析的结果吗?

$.ajax({
    method: 'GET',
    url: '/-pathSomething-/--ExampleOnly--',
    data: { sample: sample, sample: sample, sample: sample },
    success: function (result) {
        var ExamDislayQNChoiceML = JSON.parse(result);
    }
});

它看起来像

我不知道如何做,所以我没有太多的代码显示..
预期输出。随机

{ QuesNo: 3, QuesID: 3, ... }
{ QuesNo: 1, QuesID: 1, ... }
{ QuesNo: 4, QuesID: 4, ... }
{ QuesNo: 2, QuesID: 2, ... }
{ QuesNo: 5, QuesID: 5, ... }
b1zrtrql

b1zrtrql1#

使用Fisher-Yates shuffle算法这里有一个文档链接:https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle和以下是如何使用它来移动对象数组的示例

$.ajax({
    method: 'GET',
    url: '/-pathSomething-/--ExampleOnly--',
    data: { sample: sample, sample: sample, sample: sample },
    success: function (result) {
        var ExamDislayQNChoiceML = JSON.parse(result);
        shuffleArray(ExamDislayQNChoiceML);
        console.log(ExamDislayQNChoiceML); // shuffled array
    }
});

function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
}
mec1mxoz

mec1mxoz2#

这可以满足你的要求

let myJSON = {
  "name": "John",
  "age": 30,
  "city": "New York"
};

let myArray = Object.entries(myJSON);

for (let i = myArray.length - 1; i > 0; i--) {
  const j = Math.floor(Math.random() * (i + 1));
  [myArray[i], myArray[j]] = [myArray[j], myArray[i]];
}

myJSON = Object.fromEntries(myArray);

console.log(myJSON);

这将是输出

{
  "city": "New York",
  "name": "John",
  "age": 30
}
pqwbnv8z

pqwbnv8z3#

假设您想对questions对象数组进行 Shuffle :可以将Math.random()传递给Array.sort()方法。Math.random()返回0到1之间的浮点数。当Math.random()的结果减去0.5时,Array.sort()比较函数将返回随机正值或负值,因此数组将被打乱:

const shuffleArray = arr => arr.sort(() => Math.random() - 0.5);
const shuffledArr = shuffleArray(arr);

相关问题