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

慕哥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。由于我没有足够的声誉,我无法对第一篇文章发表评论。:)
添加回答
举报
0/150
提交
取消