解构数组中的Javascript对象

时间:2018-10-02 11:12:54

标签: javascript

我有一个对象数组:

var myArrayOfObjects = [
                {Attempt: 1, level: 8, Score: 10},
                {Attempt: 2, level: 9, Score: 8},
                {Attempt: 3, level: 3, Score: 7},
                {Attempt: 4, level: 4, Score: 9},
                {Attempt: 5, level: 3, Score: 5},
                {Attempt: 6, level: 1, Score: 8}];


  console.log(myArrayOfObjects);

尝试可以是无限的。级别和分数都是介于1到10之间的数字。但是在这个问题中,分数对我而言无关紧要。

我要找出的是每次尝试记录的(最佳)方法,是否曾经尝试过某个级别,是否尝试过下面的级别以及是否尝试过上面的级别。

因此,我想要的输出将是:

//[{Attempt: 1, At this level: 0, Above this level: 0, Below this level: 0}; 
//{Attempt: 2, At this level: 0, Above this level: 0, Below this level: 1}; 
//{Attempt: 3, At this level: 0, Above this level: 2, Below this level: 0};
//{Attempt: 4, At this level: 0, Above this level: 2, Below this level: 1};
//{Attempt: 5, At this level: 1, Above this level: 3, Below this level: 0};
//{Attempt: 6, At this level: 0, Above this level: 5, Below this level: 0}];

关于如何使用纯Javascript实现此目标的任何想法?

2 个答案:

答案 0 :(得分:0)

请查看他的代码。它可能会也可能不会帮助您:)

var levels = [];

// Create attemp like cerateAttempt(levelNumber, score)
createAttempt(0, 10);
createAttempt(0, 13);
createAttempt(0, 14);
createAttempt(0, 15);

// Log all attempts for lvl 0
for(let i = 0; i < levels[0].attempts.length; i++) {
  console.log("-------------------")
  console.log("Attempt: " + i)
  console.log("Score: " + levels[0].attempts[i].score);
  if(!levels[0].attempts[i + 1]) console.log("Score after: None -> last score")
  else console.log("Score after: " + levels[0].attempts[i + 1].score);
  if(!levels[0].attempts[i - 1]) console.log("Score before: None -> first score");
  else console.log("Score before: " + levels[0].attempts[i - 1].score); 
}

function createAttempt(lvl, score) {
  if(typeof(levels[lvl]) == "undefined") {
    levels[lvl] = {};
    levels[lvl].attempts = [];
  }
  levels[lvl].attempts.push({score: score});
}

答案 1 :(得分:0)

一个简单的循环和一个跟踪每个级别的尝试次数的数组将完成:

function sum(arr) { return arr.reduce((a, b) => a + b, 0); }

let attempts = [];
for (const [index, obj] of myArrayOfObjects.entries()) {
    console.assert(index + 1 == obj.Attempt); // ensure input is sorted by attempt
    console.log(`Attempt ${obj.Attempt},
    At this level: ${attempts[obj.level] || 0},
    Above this level: ${sum(attempts.slice(obj.level+1))},
    Below this level: ${sum(attempts.slice(0, obj.level))}`); 
    attempts[obj.level] = (attempts[obj.level] || 0) + 1; // increase count for this level
}

您还可以将结果放入新对象中,并将结果放入数组中。