亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在數組中查找對象,查找 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 關注
  • 156 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號