如何在 javascript 中的未知深度对象数组中找到特定 属性 值的最大深度?

How do I find the maximum depth of a particular property value in an array of objects of unknown depth in javascript?

我有一个深度未知的对象数组,如下所示:

var mainArray = [
    {
        "Application": "noun",
        "Dependencies": [
            {
                "Application": "ant"
            },
            {
                "Application": "ball"
            },
            {
                "Application": "cat"
            },
            {
                "Application": "dog"
            },
            {
                "Application": "insect",
                "Dependencies": [
                    {
                        "Application": "cat"
                    },
                    {
                        "Application": "lion"
                    }
                ]
            },
            {
                "Application": "goat"
            },
            {
                "Application": "horse"
            },
            {
                "Application": "insect",
                "Dependencies": {
                    "Application": "ant"
                }
            },
            {
                "Application": "jaguar"
            },
            {
                "Application": "kite"
            },
            {
                "Application": "lion"
            },
            {
                "Application": "monkey",
                "Dependencies": {
                    "Application": "dog",
                    "Dependencies": [
                        {
                            "Application": "ant",
                            "Dependencies": [
                                {
                                    "Application": "bell"
                                },
                                {
                                    "Application": "boar"
                                },
                                {
                                    "Application": "king",
                                    "Dependencies": {
                                        "Application": "lion"
                                    }
                                },
                                {
                                    "Application": "pig"
                                },
                                {
                                    "Application": "skunk",
                                    "Dependencies": [
                                        {
                                            "Application": "cat"
                                        },
                                        {
                                            "Application": "rat"
                                        },
                                        {
                                            "Application": "boar",
                                            "Dependencies": {
                                                "Application": "dog",
                                                "Dependencies": [
                                                    {
                                                        "Application": "apple",
                                                        "Dependencies": [
                                                            {
                                                                "Application": "tree"
                                                            },
                                                            {
                                                                "Application": "lion"
                                                            }
                                                        ]
                                                    },
                                                    {
                                                        "Application": "animal",
                                                        "Dependencies": [
                                                            {
                                                                "Application": "rat"
                                                            },
                                                            {
                                                                "Application": "boar"
                                                            },
                                                            {
                                                                "Application": "kite"
                                                            }
                                                        ]
                                                    }
                                                ]
                                            }
                                        },
                                        {
                                            "Application": "ball"
                                        },
                                        {
                                            "Application": "rat"
                                        }
                                    ]
                                },
                                {
                                    "Application": "nice"
                                },
                                {
                                    "Application": "soap"
                                },
                                {
                                    "Application": "new",
                                    "Dependencies": [
                                        {
                                            "Application": "cot"
                                        },
                                        {
                                            "Application": "bed"
                                        }
                                    ]
                                },
                                {
                                    "Application": "house"
                                }
                            ]
                        },
                        {
                            "Application": "things",
                            "Dependencies": [
                                {
                                    "Application": "dress"
                                },
                                {
                                    "Application": "pant"
                                },
                                {
                                    "Application": "shoe"
                                },
                                {
                                    "Application": "tie"
                                },
                                {
                                    "Application": "shirt"
                                }
                            ]
                        }
                    ]
                }
            }
        ]
    },
    {
        "Application": "pronoun",
        "Dependencies": [
            {
                "Application": "ant"
            },
            {
                "Application": "cat"
            },
            {
                "Application": "dog"
            },
            {
                "Application": "lion"
            },
            {
                "Application": "insect"
            }
        ]
    }
]

我需要在对象数组中找到 属性 值的最大深度,例如 antballcat 等。 在上面的对象数组中,我有两个对象,即 nounpronoun。我需要找到 nounpronoun 对象中每个 属性 值的最大深度。 例如,如果我们将 "Application": "noun" 作为级别 1,那么值 antnoun 对象中首先出现在级别 2,然后是级别 3,最后是级别 4。因此,noun 对象中 ant 的最大深度为 4。类似地,相同的 ant 值出现在 pronoun 对象的第 2 层。因此,pronoun 对象中 ant 的最大深度为 2。这样,我需要找到所有值(蚂蚁、球、猫、狗、昆虫、狮子等)的最大深度.

所需的输出应如下所示:

[
    {
        "value": "ant",
        "enrichment": {
            "applicationTier": "noun:4, pronoun:2, default:4"
        },
        "attribute": "application_tier"
    },
    {
        "value": "ball",
        "enrichment": {
            "applicationTier": "noun:6, default:6"
        },
        "attribute": "application_tier"
    },
    {
        "value": "cat",
        "enrichment": {
            "applicationTier": "noun:6, pronoun:2, default:6"
        },
        "attribute": "application_tier"
    },
    {
        "value": "dog",
        "enrichment": {
            "applicationTier": "noun:7, pronoun:2, default:7"
        },
        "attribute": "application_tier"
    },
    {
        "value": "insect",
        "enrichment": {
            "applicationTier": "noun:2, pronoun:2, default:2"
        },
        "attribute": "application_tier"
    },
    {
        "value": "lion",
        "enrichment": {
            "applicationTier": "noun:9, pronoun:2, default:9"
        },
        "attribute": "application_tier"
    }
    .......
    .......
    .......
    .......
]

在上面的输出中,enrichment对象表示nounpronoun对象中属性的最大深度。这里,defaultnounpronoun 深度中的最大深度。唯一的问题是输出应该与上面的输出完全一样。请帮忙。

下面介绍的是实现所需 objective.

的一种可能方法

代码段

// helper method - recursively count depth
const recurCount = (dep, type, currRes, level) => {
  // de-structure to access app & dep
  const { Application, Dependencies = null } = dep;
  
  // logical nullish assignment of app, noun/pronoun, default
  currRes[Application] ??= {};
  currRes[Application][type] ??= level + 1;
  currRes[Application].default ??= level + 1;
  
  // if noun or pronound depth "level" is higher, update it
  if (currRes[Application][type] <= level) {
    currRes[Application][type] = level + 1;
  };
  // update "default" is depth "level" is higher
  if (currRes[Application].default <= level) {
    currRes[Application].default = level + 1;
  };
  
  // if dep is not null
  if (Dependencies) {
    if (Array.isArray(Dependencies)) {          // dep is an array
      return Dependencies.reduce(               // use ".reduce" to iterate & get result
        (acc, depElt) => ({
          ...acc,
          ...recurCount(                        // recursive call for nested dep
            depElt, type, currRes, level + 1
          )
        }),
        currRes                                     // initially set to current-result
      )
    } else if (typeof Dependencies === 'object') {  // dep is an object
      return {
        ...currRes,
        ...recurCount(                              // recursive call for nested dep
          Dependencies, type, currRes, level + 1
        )
      };
    }
  };
  
  // if no conditions met, do not recurse. 
  // simply return current result object
  return currRes;
};

// helper method to "sort" the "enrichments" 
// to match the "noun:x, pronoun:y, default:z" format
const mySort = ([ak], [bk], list) => {
  const newList = [...list, 'default'];
  return newList.indexOf(ak) - newList.indexOf(bk);
};

// the main depth-counter method
const myCounter = (arr, list) => (
  Object.entries(                 // transform intermediate result-object into array
    arr
    .filter(                      // filter to keep only noun, pronoun
      ({ Application }) => list.includes(Application)
    )
    .reduce(                      // iterate for noun, pronoun dep-arrays
      (fin, { Application, Dependencies }) => ({
        ...fin,
        ...(                      // for each dep-array, iterate over its elements
          Dependencies.reduce(
            (acc, depElt) => ({
              ...acc,
              ...recurCount(depElt, Application, fin, 1)
            }),
            fin
          )
        )
      }),
      {}
    )
  ).map(                        // transform key-value array to desired objective format
    ([value, vobj]) => ({
      value,
      "enrichment": {
        applicationTier: Object.entries(vobj)
        .sort((a, b) => mySort(a, b, list))
        .map(
          ([k, v]) => `${k}:${v}`
        ).join(', ')
      },
      "attribute": "application_tier"
    })
  )
);

// given array
const mainArray = [{
    "Application": "noun",
    "Dependencies": [{
        "Application": "ant"
      },
      {
        "Application": "ball"
      },
      {
        "Application": "cat"
      },
      {
        "Application": "dog"
      },
      {
        "Application": "insect",
        "Dependencies": [{
            "Application": "cat"
          },
          {
            "Application": "lion"
          }
        ]
      },
      {
        "Application": "goat"
      },
      {
        "Application": "horse"
      },
      {
        "Application": "insect",
        "Dependencies": {
          "Application": "ant"
        }
      },
      {
        "Application": "jaguar"
      },
      {
        "Application": "kite"
      },
      {
        "Application": "lion"
      },
      {
        "Application": "monkey",
        "Dependencies": {
          "Application": "dog",
          "Dependencies": [{
              "Application": "ant",
              "Dependencies": [{
                  "Application": "bell"
                },
                {
                  "Application": "boar"
                },
                {
                  "Application": "king",
                  "Dependencies": {
                    "Application": "lion"
                  }
                },
                {
                  "Application": "pig"
                },
                {
                  "Application": "skunk",
                  "Dependencies": [{
                      "Application": "cat"
                    },
                    {
                      "Application": "rat"
                    },
                    {
                      "Application": "boar",
                      "Dependencies": {
                        "Application": "dog",
                        "Dependencies": [{
                            "Application": "apple",
                            "Dependencies": [{
                                "Application": "tree"
                              },
                              {
                                "Application": "lion"
                              }
                            ]
                          },
                          {
                            "Application": "animal",
                            "Dependencies": [{
                                "Application": "rat"
                              },
                              {
                                "Application": "boar"
                              },
                              {
                                "Application": "kite"
                              }
                            ]
                          }
                        ]
                      }
                    },
                    {
                      "Application": "ball"
                    },
                    {
                      "Application": "rat"
                    }
                  ]
                },
                {
                  "Application": "nice"
                },
                {
                  "Application": "soap"
                },
                {
                  "Application": "new",
                  "Dependencies": [{
                      "Application": "cot"
                    },
                    {
                      "Application": "bed"
                    }
                  ]
                },
                {
                  "Application": "house"
                }
              ]
            },
            {
              "Application": "things",
              "Dependencies": [{
                  "Application": "dress"
                },
                {
                  "Application": "pant"
                },
                {
                  "Application": "shoe"
                },
                {
                  "Application": "tie"
                },
                {
                  "Application": "shirt"
                }
              ]
            }
          ]
        }
      }
    ]
  },
  {
    "Application": "pronoun",
    "Dependencies": [{
        "Application": "ant"
      },
      {
        "Application": "cat"
      },
      {
        "Application": "dog"
      },
      {
        "Application": "lion"
      },
      {
        "Application": "insect"
      }
    ]
  }
];

// list of values used as "enrichments"
const listOfEnrichments = ["noun", "pronoun"];

// call the depth-counter method & console.log result array
console.log('depth-counted result array: ', myCounter(mainArray, listOfEnrichments));
.as-console-wrapper { max-height: 100% !important; top: 0 }

说明

在上面的代码段中添加了内联评论。