6

I have the following code, and I'm trying to get the value by the int

const fruit = Object.freeze({ Apple: 0, Banana: 1, Cherry: 2});
const myFruit = 1;

alert(fruit[myFruit]);//undefined

alert(fruit(myFruit));//not a function (obviously)

I would like the alert to provide the name of the fruit, so in this case to alert Banana as it's 1

Is this possible? I'm not using any framework, so please no JQuery/Angular/React etc. Just Javascript.

Do I have to loop through to find the match because the following won't work either:

alert(fruit.length);
4
  • 2
    What's plan? Try alert(fruit.Apple). Commented Mar 27, 2019 at 19:04
  • The set of object properties provides a one-directional mapping from property name (a string) to property value (anything). Properties don't have anything that should be thought of as a "useful" ordering; in any order, the mapping still holds in exactly the same way. Commented Mar 27, 2019 at 19:05
  • Sorry @pointy, updated Commented Mar 27, 2019 at 19:09
  • 1
    if you have to access the items by index, the right datatype might be arrays and not objects. const fruit = Object.freeze(['Apple', 'Banana', 'Cherry']); const myFruit = 1; console.log(fruit[myFruit]);//undefined Commented Mar 27, 2019 at 19:13

5 Answers 5

4

Do I have to loop through to find the match...

Yes. Objects provide lookup by property name, but not by property value. So for instance:

const fruitName = Object.keys(fruit).find(name => fruit[name] === myFruit);

Live Example:

const fruit = Object.freeze({ Apple: 0, Banana: 1, Cherry: 2});
const myFruit = 1;

const fruitName = Object.keys(fruit).find(name => fruit[name] === myFruit);

console.log(fruitName);

That gets an array of the names of the properties, then uses Array.prototype.find to find the first one with a matching value for myFruit.

Sign up to request clarification or add additional context in comments.

1 Comment

That gets an array of the names of the properties, then uses Array.prototype.find to find the first one with a matching value for myFruit. Sorry I can only give 1 x +1 , but that explanation of why is amazing
4

This is how typescript handles enums. Create an object which which points the Apple key to 0 and 0 back to Apple. So, it works both ways. This way, you don't have to loop through the object's keys and get back the key using a number everytime

const fruit = {};
fruit[fruit["Apple"] = 0] = "Apple";
fruit[fruit["Banana"] = 1] = "Banana";
fruit[fruit["Cherry"] = 2] = "Cherry";

console.log(fruit.Banana)
console.log(fruit[2])

That is just a fancy way of writing:

const fruit = {
  Apple: 0,
  Banana: 1,
  Cherry: 2,
  0: "Apple",
  1: "Banana",
  2: "Cherry"
}

Comments

1

You should use the key not the value :

 fruit["Banana"]

To do search in an object you can process like that:

const fruit = Object.freeze({
  Apple: 0,
  Banana: 1,
  Cherry: 2
});
const myFruit = 1;

console.log("expected return undefined =>", fruit[1]);

console.log("expected return 1 =>", fruit["Banana"]);

// to do search 


Object.keys(fruit).forEach(el => {

  if (fruit[el] === myFruit)
    console.log(el)
})

Comments

0

JavaScript itself doesn't have enums and it doesn't have an obvious way of reading an object's property name by accessing it by the value. However, if you're willing to make your code looks a bit funny, you could try to do what TypeScript does when it compiles enums into JavaScript object.

// TypeScript code…
enum Fruits {
    Apple, Banana
}

// … compiles to this JavaScript.
var Fruits;
(function (Fruits) {
    Fruits[Fruits["Apple"] = 0] = "Apple";
    Fruits[Fruits["Banana"] = 1] = "Banana";
})(Fruits || (Fruits = {}));

It basically simultaneously assigns a key to its value and then makes the value into a key that will hold the the original key. That way you can access this map and get the name you want.

const myFruit = 1
Fruit[myFruit] // => "Banana"

Implementation wise you could go with something like that to avoid the "nastiness" of the machine generated code.

function createEnum(enumeration) {
  const result = Object
    .entries(enumeration)
    .reduce((result, [key, value]) => {
      result[result[key] = value] = key
      return result
    }, {})
  return Object.freeze(result)
}

const fruits = createEnum({Apple: 0, Banana: 1})

fruits[1] // => "Banana"

Comments

0

Hi try with this:

const fruit = Object.freeze({
  Apple: 0,
  Banana: 1,
  Cherry: 2
});
const myFruit = 1;

Object.keys(fruit).forEach((name) => {if(fruit[name] === myFruit) alert(name)})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.