ES6 - 在嵌套数组中查找数据 [英] ES6 - Finding data in nested arrays

查看:746
本文介绍了ES6 - 在嵌套数组中查找数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ES6中使用查找过滤器我很乐意通过迭代来查找数组中的元素一个值。

In ES6 using find or filter I'm quite comfortable iterating through to find an element in an array using a value.

但是,我试图根据嵌套数组中的值从父数组中获取值。

However, I'm trying to get a value from a parent array based upon a value from a nested array.

例如,在此数据结构中:

For example, in this data structure:

products: [
  {
    id: 01,
    items: [
      {
        id: 01,
        name: 'apple'
      },
      {
        id: 02,
        name: 'banana'
      },
      {
        id: 03,
        name: 'orange'
      }
    ]
  },
  {
    id: 02,
    items: [
      {
        id: 01,
        name: 'carrot'
      },
      {
        id: 02,
        name: 'lettuce'
      },
      {
        id: 03,
        name: 'peas'
      }
    ]
  },
  {
    id: 03,
    items: [
      {
        id: 01,
        name: 'eggs'
      },
      {
        id: 02,
        name: 'bread'
      },
      {
        id: 03,
        name: 'milk'
      }
    ]
  }
]

如果我知道名称或<$对象 milk 的c $ c> id ,有没有办法找出它嵌套在的元素的id?

If I know the name or id of the object milk, is there a way to find out the id of the element it's nested within?

目前我有这个:

products.find((product) => {
  product.find((prod) => {
    return prod.name === 'milk';
  });
});

仅返回包含 milk 的对象。

推荐答案

您必须从外部查找的回调中返回一些内容。实际上,对于内部迭代,您不应该使用 find 而是 some 返回一个布尔值,表示在arrray中是否存在符合条件的元素:

You have to return something from the callback of the outer find. In fact, for the inner iteration you shouldn't use find but rather some that returns a boolean for whether an element matching the condition exists within the arrray:

products.find((product) => {
  return product.items.some((item) => {
//^^^^^^
    return item.name === 'milk';
  });
});

或简称:

products.find(product => product.items.some(item => item.name === 'milk'));

然后检查是否找到了什么(不是 null !)并获取其 .id ,结果应为 03 。或者,您可以过滤以获取包含牛奶作为项目的产品,然后将所有结果映射到其ID:

Then check whether find found something (not null!) and get its .id, the result should be 03. Alternatively, you can filter for the products containing milk as an item and then map all the results to their id:

products.filter(product =>
  product.items.some(item => item.name === 'milk');
).map(product =>
  product.id
) // [03]

这篇关于ES6 - 在嵌套数组中查找数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆