Oliver D
Oliver D

Reputation: 2889

How to get key value based on array name?

I have an object containing keys in English and values in the Arabic language,

and I want to check if these value == Arabic values return his key

sample

Object

service: {
    Plumber: 'سباكة',
    Electricity: 'الكهرباء',
    Dyeing: 'دهانات',
    Satellite: 'تلفاز ستالايت',
    Cleaning: 'التنظيف',
    Air: 'المكيفات',
  },

Arrays

['التنظيف','سباكة']

so after invoked helper function, i made the result should be this

['Plumber','Cleaning'] // in english

here's helper function i tried

_getKeyByValue = (object, arr) => {
    console.log('engKeys', Object.keys(object)); // eng keys
    let name = arr.map(item => item); // "arr values"
    return Object.keys(object).find(key => object[key] === name);
  };

here's how i call

 let serv = this._getKeyByValue(englishObject, arrabicArray);
 console.log(serv);

but it does not work, it returns undefined

Upvotes: 1

Views: 51

Answers (2)

palaѕн
palaѕн

Reputation: 73926

Your code did not work because:

let name = arr.map(item => item);

returns an array and inside

.find(key => object[key] === name);

you are trying to compare a string with an array which is always false.

Also, you are using .find() method, which only returns the value of the first element in the provided array. You need to use .filter() method instead to return all of the matches based on arrabicArray.

WORKING DEMO:

const englishObject = {
    Plumber: 'سباكة',
    Electricity: 'الكهرباء',
    Dyeing: 'دهانات',
    Satellite: 'تلفاز ستالايت',
    Cleaning: 'التنظيف',
    Air: 'المكيفات',
  };
const arrabicArray = ['التنظيف', 'سباكة'];

const _getKeyByValue = (object, arr) => {
  return Object.keys(object).filter(key => arr.includes(object[key]));
};

let serv = _getKeyByValue(englishObject, arrabicArray);
console.log(serv);
//['Plumber','Cleaning'] // in english

Upvotes: 1

Titus
Titus

Reputation: 22474

You can reduce the object's entries, here is an example:

const service = {
  Plumber: 'سباكة',
  Electricity: 'الكهرباء',
  Dyeing: 'دهانات',
  Satellite: 'تلفاز ستالايت',
  Cleaning: 'التنظيف',
  Air: 'المكيفات',
};

const arr = ['التنظيف', 'سباكة'];

const result = Object.entries(service).reduce((a, [key, value]) => {
  if (arr.includes(value)) {
    a.push(key);
  }
  return a;
}, []);

console.log(result);

And to deal with duplicates, you can clear the values from arr as you find matches:

const service = {
  Plumber: 'سباكة',
  Electricity: 'الكهرباء',
  Dyeing: 'دهانات',
  Satellite: 'تلفاز ستالايت',
  Cleaning: 'التنظيف',
  Air: 'المكيفات',
  Duplicate: 'سباكة',
};

let arr = ['التنظيف', 'سباكة'];

const result = Object.entries(service).reduce((a, [key, value]) => {
  if (arr.includes(value)) {
    arr = arr.filter(v => v !== value);
    a.push(key);
  }
  return a;
}, []);

console.log(result);

Upvotes: 1

Related Questions