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.
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.
Share Improve this question edited Dec 19, 2019 at 3:11 unflores 1,8102 gold badges16 silver badges37 bronze badges asked Dec 18, 2019 at 22:24 justleadjustlead 211 silver badge2 bronze badges 3
-
playerParameters["Facial_Hair"]
will give you 0, why would you want index from object? – bob 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
. – unflores Commented Dec 19, 2019 at 0:03 - Does this answer your question? Find index of object in javascript using its property name – vinS Commented Dec 19, 2019 at 3:47
5 Answers
Reset to default 3Object 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.
you can do this
const keys = Object.keys(playerParametrs);
const requiredIndex = keys.indexOf('whateveryouwant');
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
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;
let index = playerParametrs.findIndex((val, index) =>
Object.keys(playerParametrs[index])[0] == 'blemishes'
);
this will return the index of the match property here index = 0