简体   繁体   中英

How to compare array of objects to array?

I have an array of objects and array of strings

cities = [ { id: '1', name: 'Paris'}, { id: '2', name: 'Rome'}, { id: '3', name: 'London'}, { id: '4', name: 'Barcelona'}]

userChoice = ['2','4']

I need to iterate over cities with userChoice and find name of cities by id. I guess it's going to be a nested loop, but I am strugling with it.

cities.filter(city=> userChoice.forEach(choice => choice == city.id))

You can use filter() and includes() to filter cities array by checking if a city's id is present in userChoice array.

To get just the names, you can use map() to transform the result.

 let cities = [ { id: '1', name: 'Paris'}, { id: '2', name: 'Rome'}, { id: '3', name: 'London'}, { id: '4', name: 'Barcelona'}]; let userChoice = ['2','4']; let filteredCities = cities.filter(city => userChoice.includes(city.id)); let names = filteredCities.map(city => city.name); console.log(names);

You could use a Map object to look up ID based on city.

let cityMap = new Map(cities.map(c => [c.name, c.id]));
console.log(cityMap.get("Rome")); // --> "2"

Just use a simple map, you map the array element to the city from the other array. You might want to put a null check in if you can have values that might not be in the array but for simplicity I left it out.

 const cities = [ { id: '1', name: 'Paris'}, { id: '2', name: 'Rome'}, { id: '3', name: 'London'}, { id: '4', name: 'Barcelona'}]; const userChoice = ['2','4']; const userCities = userChoice.map(val => cities.find(c => c.id === val).name); console.log(userCities)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM