我有以下数组,我尝试通过提供 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....
谢谢。
最佳答案
您可以使用filter
和some
方法。这种方法将过滤数组,并且您的数组将仅包含所需的项目:
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/