Reputation: 2690
I got array of objects
const countryList = [
{ name: 'Afghanistan', id: 'AF' },
{ name: 'Åland Islands', id: 'AX' },
{ name: 'Albania', id: 'AL' },
{ name: 'Algeria', id: 'DZ' }]
I want to filter the array by object "id" and get name
Here is what I have already done and it is working
getName = (id) => {
let name=[]
for (var i = 0; i < countryList.length ; i++) {
if (countryList[i].id === id) {
name.push(countryList[i]);
}
}
console.log(name[0].name)
}
Is there any better way of doing it?
Upvotes: 2
Views: 188
Reputation: 392
You could do with array.some for performance reasons, if country id is unique.
getCountryName = (countryList, id) => {
name = null;
countryList.some((x, idx) => {
result = false;
if(x.id === id) {
name = x.name;
result = true;
}
return result;
});
return name;
}
Usage is
getCountryName(countryList, 'AF')
Result is
'Afghanistan'
Upvotes: 0
Reputation: 411
I think this works too
const countryList = [
{ name: 'Afghanistan', id: 'AF' },
{ name: 'Åland Islands', id: 'AX' },
{ name: 'Albania', id: 'AL' },
{ name: 'Algeria', id: 'DZ' }];
getName=(id)=>{
countryList.filter(item=>{item.id===id})
console.log(countryList[0].name)
}
Upvotes: 0
Reputation: 36564
You can use find()
to get the object and then return the name
of that object.
const countryList = [ { name: 'Afghanistan', id: 'AF' }, { name: 'Åland Islands', id: 'AX' }, { name: 'Albania', id: 'AL' }, { name: 'Algeria', id: 'DZ' } ]
const getName = id => (countryList.find(x => x.id === id) || {}).name
console.log(getName('AX'))
console.log(getName('DZ'))
Upvotes: 0
Reputation: 53958
You could make use of find
array method:
const countryList = [
{ name: 'Afghanistan', id: 'AF' },
{ name: 'Åland Islands', id: 'AX' },
{ name: 'Albania', id: 'AL' },
{ name: 'Algeria', id: 'DZ' }];
getName = (id) => {
let country = countryList.find(c=>c.id === id);
return country !== undefined
? country.name
: 'not found';
}
console.log(getName('DZ'));
Note here that the getName
returns now a string and doesn't have any side effects like logging the found value in the console. Also the function now does exactly what it's name says, just gets the name.
For further info regrading this method, please have a look here.
Upvotes: 0
Reputation: 1
You don't need the "name" array.
getName = (id) => {
for (var i = 0; i < countryList.length ; i++) {
if (countryList[i].id === id) {
console.log(name[i].name);
}
}
}
Upvotes: 0
Reputation: 386520
You could find the name, if id
is unique and take for unknow items a default object.
const
getName = id => (countryList.find(o => o.id === id) || {}).name,
countryList = [{ name: 'Afghanistan', id: 'AF' }, { name: 'Åland Islands', id: 'AX' }, { name: 'Albania', id: 'AL' }, { name: 'Algeria', id: 'DZ' }];
console.log(getName('AL'));
console.log(getName('UK'));
Upvotes: 1