为了账号安全,请及时绑定邮箱和手机立即绑定

在数组中查找对象,查找 id 匹配子字符串的对象

在数组中查找对象,查找 id 匹配子字符串的对象

烙印99 2022-12-29 16:14:54
我从 API 获得了很多数组,但 id 的计数不同,我需要检查匹配[id = region...]并只获得这个对象。我如何使用正则表达式和来做到这一点find?(5) [{…}, {…}, {…}, {…}, {…}]0: {id: "address.7576869587107444", type: "Feature", place_type: Array(1), relevance: 1, properties: {…}, …}1: {id: "postcode.12959148828066430", type: "Feature", place_type: Array(1), relevance: 1, properties: {…}, …}2: {id: "place.14392640799224870", type: "Feature", place_type: Array(1), relevance: 1, properties: {…}, …}3: {id: "region.9375820343691660", type: "Feature", place_type: Array(1), relevance: 1, properties: {…}, …}4: {id: "country.13200156005766020", type: "Feature", place_type: Array(1), relevance: 1, properties: {…}, …}length: 5__proto__: Array(0).then(res => {        let region = /region/gi        console.log(res.data.features.find(place => place.id == region.test(place)))        setAdrress(res.data)      })
查看完整描述

2 回答

?
江户川乱折腾

TA贡献1851条经验 获得超5个赞

使用String#match

console.log(res.data.features.find(place => place.id.match(region)))

const arr = [{id: "address.7576869587107444", type: "Feature"},

{id: "postcode.12959148828066430", type: "Feature"},

{id: "place.14392640799224870", type: "Feature"},

{id: "region.9375820343691660", type: "Feature"},

{id: "country.13200156005766020", type: "Feature"}];

let region = /region/gi;

console.log(arr.find(place => place.id.match(region)))


查看完整回答
反对 回复 2022-12-29
?
慕哥9229398

TA贡献1877条经验 获得超6个赞

您可以过滤数组并使用正则表达式检查以实现该目的。

var regex = RegExp(/^region/);
var filtered_arr = arr.filter(obj => regex.test(obj.id));

filtered_arr将包含您的 id 开头的对象数组region

使用正则表达式将确保过滤所有以开头的字符串。region使用 match 之类的东西会找到region字符串中任何位置的 id。由于我没有足够的声誉,我无法对第一篇文章发表评论。:)


查看完整回答
反对 回复 2022-12-29
  • 2 回答
  • 0 关注
  • 96 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号