0

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.

0

4 Answers 4

2

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);
            }
        }
    )
Sign up to request clarification or add additional context in comments.

Comments

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'));

Comments

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; }

Comments

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' ]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.