如何在JavaScript中的无限嵌套数组中获取父ID

时间:2018-12-22 15:01:02

标签: javascript

它是标题,但我遇到了问题!

我想创建getParentId(array, id)函数。

此功能通过子ID获取父ID。

const array = [{
  id: 1,
  title: 'hello',
  children: [{
    id: 3,
    title: 'hello',
    children: [{
      id: 4,
      title:'hello',
      children: [
        { id: 5, title: 'hello'},
        { id: 6, title: 'hello'}
      ]
    },
    {
      id: 7,
      title: 'hello'
    }]
  }]
},
{
  id: 2,
  title: 'hello',
  children: [
    { id: 8, title: 'hello'}
  ]
}]
  • 此数组可能无限期嵌套

预期结果:

getParentId(array, 3) -> 1

getParentId(array, 5) -> 4

getParentId(array, 6) -> 4

getParentId(array, 8) -> 2

getParentId(array, 2) -> null

如果您能向我发送信息,我将不胜感激。

2 个答案:

答案 0 :(得分:1)

您可以采用递归方法,通过迭代实际的数组及其子级,并在找到<mat-card class="example-card mat-elevation-z" fxLayout="row wrap" fxLayoutAlign="center"> <mat-card-header> <mat-card-title> <h1 fxFlex fxFlex="100" fxFlexAlign="center">ALOE VERA For Pure <span class="title-line"></span></h1> </mat-card-title> </mat-card-header> <mat-card-content fxLayout="row wrap" fxLayoutAlign="center"> <p fxFlex fxFlex="100" fxLayoutAlign="center">Aloe Vera is very famous for its herbal products. more than three thousand five hundred years, people have recognized the healing and moisturizing properties of the aloe vera plant. Aloe Vera is well known for its soothing and calming effects and as such is a great ingredient for use in our skin care products. Aloe’s beneficial properties, result in it being ideally suited for use in skin care products to soothe and calm sensitive, delicate and dry skin; Aloe enhances natural cell renewal, improving texture and elasticity so the skin is firmer, more supple and luminous. It also nourishes and protects the scalp maintaining healthy hair.</p> <p fxFlex fxFlex="100" fxLayoutAlign="center">Natural Health Products supplies raw and bulk material of Aloe Vera plant extract used in the cosmetic, complementary medicinal, and food and beverage industries. It also supplies finished Aloe Vera products for distribution. With over 150 nutritional ingredients, Aloe Vera is one of the most powerful medicinal plants in use today and it has a variety of applications. In 1959, the FDA (Food and Drug Administration) admitted that aloe-based products had regenerative properties on tissue.</p> <p fxFlex fxFlex="100" fxLayoutAlign="center">That year represented a major breakthrough in the future implementation of products based on aloe vera. As a result, for more than 30 years, the aloe vera industry has experienced a non-stop growth.</p> </mat-card-content> </mat-card> 时停止。

id
function getParentId(array, id, parentId) {
    return array.some(o =>
            o.id === id ||
            o.children && (parentId = getParentId(o.children, id, o.id)) !== null
    )
        ? parentId
        : null;
}

const array = [{ id: 1, title: 'hello', children: [{ id: 3, title: 'hello', children: [{ id: 4, title:'hello', children: [{ id: 5, title: 'hello' }, { id: 6, title: 'hello' }] }, { id: 7, title: 'hello' }] }] }, { id: 2, title: 'hello', children: [{ id: 8, title: 'hello' }] }];

console.log(getParentId(array, 3)); // 1
console.log(getParentId(array, 5)); // 4
console.log(getParentId(array, 6)); // 4
console.log(getParentId(array, 8)); // 2
console.log(getParentId(array, 2)); // null

答案 1 :(得分:1)

尼娜·舒尔茨(Nina Scholz)的回答很好,但是如果您更喜欢,这是一种功能稍差的方法(不使用Array.some)。

const array = [{id: 1, title: 'hello', children: [{id: 3, title: 'hello', children: [{id: 4, title:'hello', children: [{ id: 5, title: 'hello'}, { id: 6, title: 'hello'}]}, {id: 7, title: 'hello'}]}]}, {id: 2, title: 'hello', children: [{ id: 8, title: 'hello'}]}];

function getParentId(array, id, parentId = null) {
  // For every entry in the array
  for (const entry of array) {
    // If the ID matches, return the current parent ID
    if (entry.id === id) {
      return parentId;
    }
    // Otherwise, call the same function on its children, passing itself as the parent.
    // If there was a match, return it.
    if (entry.children && (deeperParentId = getParentId(entry.children, id, entry.id))) {
      return deeperParentId;
    }
  }
  // No match was found
  return null;
}

console.log(getParentId(array, 3));
console.log(getParentId(array, 5));
console.log(getParentId(array, 6));
console.log(getParentId(array, 8));
console.log(getParentId(array, 2));

请注意,我对此进行了过分注释,这在编写实际代码时并不是一个好主意。这只是答案。

另外,正如我在评论中提到的,请下次分享您的尝试。