Reputation: 21
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.
Upvotes: 1
Views: 6478
Reputation: 2476
let index = playerParametrs.findIndex((val, index) =>
Object.keys(playerParametrs[index])[0] == 'blemishes'
);
this will return the index of the match property here index = 0
Upvotes: 0
Reputation: 1102
you can do this
const keys = Object.keys(playerParametrs);
const requiredIndex = keys.indexOf('whateveryouwant');
Upvotes: 3
Reputation: 112
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.
Upvotes: 3
Reputation: 1183
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;
Upvotes: 0
Reputation: 40424
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
Upvotes: 1