javascript - 从具有给定 ID 的子数组中获取值

标签 javascript arrays angular

我有以下数组,我尝试通过提供 ID 使用 .find 打印子数组值

connections = [
    {
      group: 'a',
      items: [
        {
          id: '1',
          name: 'Andre'
        },
        {
          id: '2',
          name: 'David'
        }
      ]
    },
    {
      group: 'b',
      items: [
        {
          id: '3',
          name: 'Brandon'
        }
      ]
    },
]

我在我的 Angular 应用程序中尝试了以下操作,

getUser(id) {
    this.activeItem = this.connections.items.find(data => data.id === id);
    console.log(this.activeItem);
}

我提供了正确的 ID,但收到一条错误消息,

error TS2339: Property 'items' does not exist on type....

谢谢。

最佳答案

您可以使用filtersome方法。这种方法将过滤数组,并且您的数组将仅包含所需的项目:

let connections = [
    {
      group: 'a',
      items: [
        {
          id: '1', name: 'Andre'
        },
        {
          id: '2', name: 'David'
        }
      ]
    },
    {
      group: 'b',
      items: [
        {
          id: '3', name: 'Brandon'
        }
      ]
    },
]

let id = 3;
// ONE WAY
const result = connections.filter(f=> f.items.some(s=> s.id == id))
                          .flatMap(fm => fm.items);
console.log(`result: `, result);

// OR ANOTHER WAY:
const resultWithGroup = connections.filter(f=> f.items.some(s=> s.id == id));
const resultItem = Object.assign({}, ...resultWithGroup).items.find(f => f.id == id);
console.log(`resultItem: `, resultItem);
console.log(`resultItem as an array: `, [resultItem]);

此外,还可以使用 flatMap method 。通过使用这种方法,您将获取具有所需 id 的所有项目,然后找到具有 id == 3 的第一个元素:

let connections = [
    {
      group: 'a',
      items: [
        {
          id: '1', name: 'Andre'
        },
        {
          id: '2', name: 'David'
        }
      ]
    },
    {
      group: 'b',
      items: [
        {
          id: '3', name: 'Brandon'
        }
      ]
    },
]

const result = connections.flatMap(f => f.items).find(f => f.id == id);
console.log(`result as array`, [result]);

关于javascript - 从具有给定 ID 的子数组中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58786505/

相关文章:

javascript - 统计数组中的重复项

python - 二维数组一维中的 Numpy 局部最大值

Angular:HttpClientModule 导入错误(无法解析为 NgModule 类)

javascript - 从 phonegap facebook 登录获取用户 ID

javascript - 将 AJAX 添加到 PHP 表单

Javascript:找出数组中是否至少有两个不同的值

angular - 如何删除 Apollo-Angular 及其所有依赖项?

javascript - 如何使用 sencha 中的操作列加载第二个数据网格

javascript - 将 jQuery.animate() 添加到 Knockout.js 自定义绑定(bind)?

javascript - Angular 应用程序必须在新部署后清除缓存