首页 > 解决方案 > 使用基本 JavaScript 查找嵌套对象数据

问题描述

我想遍历一个对象中的 600 多个数组项,并根据某些条件找到一个特定的项。对象中的数组称为“操作”,其项目本身就是数组。

我的目标是获取具有深度嵌套字符串“Go”的操作数组项的索引。

在下面的示例中,这将是第一个元素。我的问题是我可以检查一个数组元素是否包含“call”和“draw”,但我不知道如何测试嵌套字典“foobar”。我只有基本的 JavaScript 可用,没有特殊的库。

let json = {
  "head": {},
  "operations": [
    [
      "call",
      "w40",
      "draw",
      {
        "parent": "w39",
        "style": [
          "PUSH"
        ],
        "index": 0,
        "text": "Modify"
      }
    ],
    [
      "call",
      "w83.gc",
      "draw",
      {
        "foobar": [
          ["beginPath"],
          [
            "rect",
            0,
            0,
            245,
            80
          ],
          ["fill"],
          [
            "fillText",
            "Go",
            123,
            24
          ],
          [
            "drawImage",
            "rwt-resources/c8af.png",
          ]
        ]
      }
    ],
    [
      "create",
      "w39",
      "rwt.widgets.Menu",
      {
        "parent": "w35",
        "style": [
          "POP_UP"
        ]
      }
    ],
    [
      "call",
      "w39",
      "draw",
      {
        "parent": "w35",
        "style": [
          "POP_UP"
        ]
      }
    ]
  ]
};

let index = "";
let operationList = json.operations;
for (i = 0; i < operationList.length; i++) {
  if (operationList[i].includes('call') && operationList[i].includes('draw')) //missing another check if the dictionary "foobar" exists in this element )
  {
    index = i;
  }
}
document.write(index)

标签: javascript

解决方案


我首先要说的是,这种数据结构通常很难管理。我会建议一个方案,其中 anoperation是一个具有明确定义的属性的对象,而不仅仅是一个“东西数组”。

也就是说,您可以使用递归来搜索数组。

  • 如果数组中的任何值是另一个数组,则继续下一级递归
  • 如果任何值是对象,则搜索其值
const isPlainObject = require('is-plain-object');

const containsTerm = (value, term) => {
  // if value is an object, search its values
  if (isPlainObject(value)) {
    value = Object.values(value);
  }

  // if value is an array, search within it
  if (Array.isArray(value)) {
    return value.find((element) => {
      return containsTerm(element, term);
    });
  }

  // otherwise, value is a primitive, so check if it matches
  return value === term;
};

const index = object.operations.findIndex((operation) => {
  return containsTerm(operation, 'Go');
});

推荐阅读