1

I get a lot of arrays from API but a count of id different and I need to check for match [id = region...] and to get only this object. How I can do this using regular expressions and 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)
      })
1

2 Answers 2

1

Use 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)))

Sign up to request clarification or add additional context in comments.

1 Comment

@JessicaBulldog Glad to help.
0

You can filter the array and check with a regex to achieve that.

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

filtered_arr will contain your array of the objects where the id starts with region

Using regex will ensure that all the string which start with region will be filtered. Using something like match will find the ids which have region anywhere in the string. I couldn't comment on the first post as I don't have enough reputation. :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.