I want to turn the following object
const order = {
apple: 5,
banana: 5,
orange: 5
};
into the following object, with each key being assigned its index in the object as its value
{
apple: 0,
banana: 1,
orange: 2
}
This is the code I have but it's not working and I don't know why.
const indices = Object.keys(order).reduce(
(previousValue, currentValue, currentIndex) =>
(previousValue[currentValue] = currentIndex), {}
);
TypeError: Cannot create property 'banana' on number '0'
What am I doing wrong here?
{}to have any ordering to keys - so things likeObject.keysare not really deterministic (eg. you might not get the same thing back on on multiple calls). However, I have found in practice that the keys are generally returned in the order they were added. I would not stake any critical business functionality on this though as it could change any day without notice.