简体   繁体   English

使用基本 JavaScript 查找嵌套的 object 数据

[英]Finding nested object data using basic JavaScript

I want to loop through 600+ array items in an object and find one particular item based on certain criteria.我想遍历 object 中的 600 多个数组项,并根据特定条件找到一个特定项。 The array in the object is called "operations" and its items are arrays themselves. object 中的数组称为“操作”,其项目本身就是 arrays。

My goal is to get the index of operation's array item which has the deeply nested string "Go".我的目标是获取具有深度嵌套字符串“Go”的操作数组项的索引。

In the sample below this would be the first element.在下面的示例中,这将是第一个元素。 My problem is that I can check if an array element contains "call" and "draw" but I don't know how to test for the nested dictionary "foobar".我的问题是我可以检查一个数组元素是否包含“call”和“draw”,但我不知道如何测试嵌套字典“foobar”。 I only have basic JavaScript available, no special libraries.我只有基本的 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)

I'll preface by saying that this data structure is going to be tough to manage in general.我首先要说的是,这种数据结构通常很难管理。 I would suggest a scheme for where an operation is an object with well defined properties, rather than just an "array of stuff".我会建议一个方案,其中operation是具有明确定义的属性的 object,而不仅仅是“东西数组”。

That said, you can use recursion to search the array.也就是说,您可以使用递归来搜索数组。

  • If any value in the array is another array, continue with the next level of recursion如果数组中的任何值是另一个数组,则继续下一级递归
  • If any value is an object, search its values如果任何值为 object,则搜索其值
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');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM