-1

i have an object

const alpha = {
  a: 'apple'
  b: 'bubble'
}

the goal is to get the property name by using only the value, for example, I want to use the string apple to get the proberty name a in a form of a string.

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
ProMaker Dev
  • 105
  • 1
  • 2
  • 12

4 Answers4

1

I think you want to do something like this...

const alpha = {
  a: 'apple',
  b: 'bubble'
};

const selectKeys = (object, selector) => {
  let results = [];
  
  if (object != null) {
    results = Object.entries(object)
      .filter((e) => selector(e[1], e[0], e))
      .map((e) => e[0]);
  }
  
  return results;
};

const keys = selectKeys(alpha, (value) => value === 'apple');
console.log(keys);

This will just select all keys where the selector expression returns true. For your case thats just the name. Notice that this returns an array, because multiple keys can be returned. To get the first key simply use keys[0] or whatever.

You could get fancier and add higher order functions to make your selectors easier to read as well.

const byValue = (value) => (v) => v === value;
const a = selectKeys(object, byValue('apple'));
const a = selectKeys(object, byValue('bubble'));
Brenden
  • 1,947
  • 1
  • 12
  • 10
1

The following simple implementation will log the keys for apple in the console.

const alpha = {
  a: 'apple',
  b: 'bubble'
}


Object.entries(alpha).map(
        ([key, value]) => {
            if (value === 'apple'){
                console.log(key);
            }
        }
    )
Tejogol
  • 670
  • 8
  • 24
1

You would return a list of keys who's value matches the provided value. If you wanted the first match, just shift the value off the beginning of the result.

const alpha = {
  a: 'apple',
  b: 'bubble'
};

const keysForValue = (obj, value) =>
  Object.entries(obj)
    .filter(([, val]) => val === value)
    .map(([key]) => key);
    
console.log('Key:', keysForValue(alpha, 'bubble').shift()); // Key: b
.as-console-wrapper { top: 0; max-height: 100% !important; }
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
1

Try the below approach,

const alpha = {
  a: 'apple',
  b: 'bubble',
  c: 'bubble',
  d: 'orange',
  e: 'bubble'
}

const findKeyByValue = (obj, value) => {
  const arr = [];
  for (const prop in obj) {
    if(obj[prop] === value){
      arr.push(prop);
    }
  }
return arr;
};


findKeyByValue(alpha, 'bubble'); //[ 'b', 'c', 'e' ]
Sarun UK
  • 6,210
  • 7
  • 23
  • 48