1

I have an object, with a list inside each key. What is the best way of returning the key, if the url string matches what's in the array.

For example in the code below, 'entertainment' would be returned as "/video" is in the entertainment array.

const url = "https://example.com/video";

const verticalList = {
    autos:[],
    entertainment:["/video", "/tech"],
    foodanddrink:[],
    healthandfitness:[],
    homepage:["/home"],
    lifestyle:["/ideas", "/executive-life"],
    money:["/money-markets",],
    news:["/briefing"],
    sports:[],
    travel:[],
    weather:[]
}

1 Answer 1

4

You can use Object.entries to get a list of key-value pairs from your object and then run Array.filter to compare values against your url. In the last step you have to run Array.map to retrieve corresponding keys. String.includes can be used to check if one string is a substring of another.

const url = "https://example.com/video";

const verticalList = {
    autos:[],
    entertainment:["/video", "/tech"],
    foodanddrink:[],
    healthandfitness:[],
    homepage:["/home"],
    lifestyle:["/ideas", "/executive-life"],
    money:["/money-markets",],
    news:["/briefing"],
    sports:[],
    travel:[],
    weather:[]
}

let matches = Object.entries(verticalList)
                    .filter(([key,value]) => value.some(x => url.includes(x)))
                    .map(([key,value]) => key);

console.log(matches)

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

2 Comments

Thanks, it works great I don't fully understand what's going on, but I will read up on all these new methods on mozilla!
@JonathanDevereux sure - it's really good to get familiar with them - they can make your like easier :)

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.