1
var playerParametrs = {
    "blemishes" : 0,
    "Facial_Hair" : 0,
    "ChinShape" : 0, 
    "NeckWidth" : 0
}

How can I get the index of a property? Like, for instance, indexOf("blemishes") is 0.


3
  • playerParameters["Facial_Hair"] will give you 0, why would you want index from object? Commented Dec 18, 2019 at 23:37
  • 1
    @justlead I think you are misunderstanding what an object is and how they work. An object doesn't have indexes in the same way that an array does. An object has keys and values. Technically an object can have its keys dereferenced like an array, or like an object in javascript. So in your example playerParametrs['blemishes'] == playerParametrs.blemishes == 0. Commented Dec 19, 2019 at 0:03
  • Does this answer your question? Find index of object in javascript using its property name Commented Dec 19, 2019 at 3:47

5 Answers 5

3

Object properties don't have indexes. You'd have to turn it into an array eg.

var arr = Object.entries(playerParametrs); // [["blemishes", 0], ["Facial_Hair", 0], ["ChinShape", 0], ["NeckWidth", 0]]

Then you can use a higher array function to find the index of "blemishes":

arr.findIndex(e => e[0] === "blemishes");  // 0

Note that the properties will always be in the order they were inserted in.

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

Comments

3

you can do this

const keys = Object.keys(playerParametrs);
const requiredIndex = keys.indexOf('whateveryouwant');

Comments

1

That's a simple object, what you want is just the property value, not the index. You access either using . or [].

Check: Property accessors

console.log(playerParametrs.Facial_Hair); // 0
console.log(playerParametrs["Facial_Hair"]); // 0

Comments

0

There isn't a need to access the index, objects store and access their information by key:value pairs. You can input them in any order and they are accessed by the key.

If you are trying to use the value:

if (playerParametrs.Facial_Hair === 0) {
  // do something
}

If you're trying to update the value:

playerParametrs.Facial_Hair = 1;

Comments

0
let index = playerParametrs.findIndex((val, index) =>
  Object.keys(playerParametrs[index])[0] == 'blemishes'
);

this will return the index of the match property here index = 0

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.