map 函数和 for 循环的问题。为什么结果总是“8”?

Problem with map function and for loop. Why is the result always "8"?

我对这段代码有疑问。对于 editorJSON 中的每个项目,我想访问前一个问题的 ID 并将其 return 作为“inputcontext”(例如,对于问题 ID 2,我想访问问题 ID 1,等等)。我试图用下面的代码来实现这个,但是 console.log() 命令总是给我“8”。

const editorJSON = {
  1: {
    id: 1,
    name: "Question"
  },
  2: {
    id: 2,
    name: "Question"
  },
  3: {
    id: 3,
    name: "Tipp"
  },
  4: {
    id: 8,
    "name": "Question"
  }
}

Object.keys(editorJSON).map((key, index) => {
  const inputcontext = () => {
    let inputcontext = "";
    var l = Object.keys(editorJSON).length;
    for (i = l; l < 1; i--) {
      if (editorJSON[i].name === "Question") {
        let inputcontext = editorJSON[i].id;
        return inputcontext
      }
    }
  }
  console.log(inputcontext())
})

您可以过滤对象的键并映射之前找到的键。这种方法依赖于具有索引的键的顺序(32 位正整数)。

const
    data = { 1: { id: 1, name: "Question" }, 2: { id: 2, name: "Question" }, 3: { id: 3, name: "Tipp" }, 4: { id: 8, name: "Question" } },
    previousQuestions = Object
        .keys(data)
        .filter(k => data[k].name === 'Question')
        .map((k, i, a) => [data[k].id, data[a[i - 1]]?.id]);

console.log(previousQuestions);

由于数字键总是按升序迭代,您可以循环遍历前面的元素,直到使用 Array#map 找到一个问题,它提供原始数组作为回调的第三个参数。

const editorJSON = {
  1: {
    id: 1,
    name: "Question"
  },
  2: {
    id: 2,
    name: "Question"
  },
  3: {
    id: 3,
    name: "Tipp"
  },
  4: {
    id: 8,
    "name": "Question"
  }
};

const res = Object.keys(editorJSON).map((key, index, arr) => {
  let inputcontext;
  for(let i = key - 1; i > 0; i--){
    if(editorJSON[i]?.name === "Question"){
      inputcontext = editorJSON[i].id;
      break;
    }
  }
  return {...editorJSON[key], inputcontext};
});
console.log(res);