以匹配IDS JAVASCRIPTIND结合所有对象 我正在尝试从我的学生数组中获取所有具有匹配ID的对象,并从中获取其他属性值... 例如,我的数组看起来像这样: const学生= [ {id:1,名称:'cal',

问题描述 投票:0回答:2
const students = [ {id: 1, name: 'Cal', location: 'McHale' }, {id: 2, name: 'Courtney', location: 'Sydney Hall' }, {id: 1, name: 'Cal', location: 'Syndey hall' } ]

因此,我的预期输出将抓住所有ID的实例:1.

{id: 1, name: 'Cal', location: 'McHale' }, {id: 1, name: 'Cal', location: 'Syndey hall' }
我最终想删除重复的名称并在列表中显示……(但这是在线的。现在,我只想抓住匹配的对象)。

Id: 1 Name: Cal Location: McHale Syndey Hall

我尝试了:

const result = _.find(students, {student_id: studentId});

但这似乎不起作用,它只是返回具有该ID的对象之一。

{id: 1, name: 'Cal', location: 'McHale' },
我可以做这项工作?

I将调查

滤波器

函数。它已构建为JavaScript。
这里是其工作原理的一个例子。您需要做的就是找到一种方法来确定其是否具有适当ID的函数。

function isBigEnough(value) { return value >= 10; } var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); // filtered is [12, 130, 44]

javascript arrays lodash
2个回答
30
投票

Source

如果您看到的文档,请列出

列表收集元素,返回第一个元素谓词返回真相。
您应该将

_.find方法用于您想要的

对收集元素的介绍,返回所有元素谓词的数组返回真相。

9
投票

一样 _.filter

    

const result = _.filter(students, {student_id: studentId});

toind cind将始终返回第一个匹配元素,无论其他元素可能与您的病情匹配多少。 如果您想提取所有匹配元素,则需要使用.filter方法。

实现是相同的,但是结果从对象(.find(.find())到数组(.filter())

© www.soinside.com 2019 - 2025. All rights reserved.