javascript - 对数组中的对象进行操作

标签 javascript arrays reactjs object

这对我来说是一项具有挑战性的任务。我有一个对象数组。我需要遍历一个数组,如果有“消息”键,将它添加到一个新数组中。但是这里有一件棘手的事情。如果“render”为真,我需要获取“stageID”(例如在第一个元素 stadeID = 3 中)并移动到该数组中的第三个元素,如果有则获取“message”,再次将其添加到数组并检查对于“渲染”状态,一直循环直到渲染为假。如果元素中没有“消息”键,但渲染为真,无论如何我需要通过它的 stageID 移动到元素。

P/S 我总是需要从第一个元素获取消息,是否无关紧要 渲染是否为真

[
  {
    "algID": 0,
    "render": true,
    "message": "first message",
    "stageID": "3"
  },
  {
    "algID": 0,
    "render": false,
    "message": "second message",
    "message_type": "text"
  },
  {
    "algID": 0,
    "render": true,
    "message": "third message",
    "message_type": "text",
    "stageID": "5"
  },
  {
    "algID": 0,
    "render": false
  },
  {
    "algID": 0,
    "render": false,
    "stageID": "4"
  },
  {
    "algID": 0,
    "render": false
  }
]

这是我的功能。我将第一个元素“消息”添加到数组,检查“渲染”,但我不知道它如何使用“stageID”循环移动通过数组

displayData(step) {
  let arrayWithMessage=[]
      for (let z = 0; z < step.length; z++) {
        if ("message" in step[z]) {
          arrayWithMessage.push(step[z].message)
        }
        if (step[z].render === true) {
          console.log("reder true", step[step[z].stageID - 1])
        }
      }
  }

预期输出:['第一条消息','第三条消息']

最佳答案

您可以迭代数组并将下一个元素或 stageID - 1 作为新索引。

var data = [{ algID: 0, render: true, message: "first message", stageID: "3" }, { algID: 0, render: false, message: "second message", message_type: "text" }, { algID: 0, render: true, message: "third message", message_type: "text", stageID: "5" }, { algID: 0, render: false }, { algID: 0, render: false, stageID: "4" }, { algID: 0, render: false }],
    result = [],
    i = 0;

while (data[i]) {
    if (data[i].message) result.push(data[i].message);
    if (data[i].render) {
        i = data[i].stageID - 1;
        continue;
    }
    i++;
}

console.log(result);

关于javascript - 对数组中的对象进行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55727531/

相关文章:

javascript - jQuery on() 无法正常工作

javascript - ExtJS 多 View 实例

java - 按字母顺序正确排序数组时出现问题

html - react js css 样式在与标题字符串相同的行上获取 Font Awesome 图标

reactjs - 如何使用 reactjs 提交父组件中的子值?

javascript - 从 CSS 模块中访问全局类

javascript - 使用 mongo 脚本导入 JSON

javascript - 定义 JavaScript 源文件的字符编码

c - 我怎样才能再次这样做?在C中

python - 仅计算 numpy 数组的 1 列中的非零数