查找对象数组中所有与之匹配的元素

编程入门 行业动态 更新时间:2024-10-25 02:21:02
本文介绍了查找对象数组中所有与之匹配的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个对象数组

我正在像这样在数组中搜索

I am searching within the array like this

let arr = [ { name:"string 1", arrayWithvalue:"1,2", other: "that" }, { name:"string 2", arrayWithvalue:"2", other: "that" }, { name:"string 2", arrayWithvalue:"2,3", other: "that" }, { name:"string 2", arrayWithvalue:"4,5", other: "that" }, { name:"string 2", arrayWithvalue:"4", other: "that" }, ]; var item = arr.find(item => item.arrayWithvalue === '4'); console.log(item)

这应该返回一个包含这两行的数组

This should return an array with this two rows

{ name:"string 2", arrayWithvalue:"4,5", other: "that" }, { name:"string 2", arrayWithvalue:"4", other: "that" }

它仅返回一行,这是第一个匹配项.

It returns only one row which is the first match.

{ name:"string 2", arrayWithvalue:"4", other: "that" }

我不想为此使用任何外部库.如何返回所有符合条件的匹配项?

I do not want to use any external libraries for this. How can I return all the matches that match the criteria?

推荐答案

首先,Array.find()返回第一个匹配元素,undefined,如果找不到任何内容. Array.filter返回一个包含所有匹配元素的新数组,如果[]不匹配任何内容.

Two thing, first, Array.find() return the first matching element, undefined if it finds nothing. Array.filter returns a new array containing all matching elements, [] if it matches nothing.

第二件事,如果要匹配4,5,则必须查看字符串,而不要进行严格的比较.为了实现这一点,我们使用indexOf返回匹配字符串的位置,或者使用-1如果什么都不匹配.

Second thing, if you want to match 4,5, you have to look into the string and do not make strict comparaison. To make that happens we use of indexOf which is returning the position of the matching string, or -1 if it matches nothing.

示例:

const arr = [{ name: 'string 1', arrayWithvalue: '1,2', other: 'that', }, { name: 'string 2', arrayWithvalue: '2', other: 'that', }, { name: 'string 2', arrayWithvalue: '2,3', other: 'that', }, { name: 'string 2', arrayWithvalue: '4,5', other: 'that', }, { name: 'string 2', arrayWithvalue: '4', other: 'that', }, ]; const items = arr.filter(item => item.arrayWithvalue.indexOf('4') !== -1); console.log(items);

更多推荐

查找对象数组中所有与之匹配的元素

本文发布于:2023-11-29 23:31:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647961.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:与之   组中   元素   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!