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

我从 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)

      })


烙印99
浏览 176回答 2
2回答

江户川乱折腾

使用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)))

慕哥9229398

您可以过滤数组并使用正则表达式检查以实现该目的。var regex = RegExp(/^region/); var filtered_arr = arr.filter(obj => regex.test(obj.id));filtered_arr将包含您的 id 开头的对象数组region使用正则表达式将确保过滤所有以开头的字符串。region使用 match 之类的东西会找到region字符串中任何位置的 id。由于我没有足够的声誉,我无法对第一篇文章发表评论。:)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript