Here is a descriptive implementation of a function which adds a key to an object at a specific index.
/**
* adds a key-value pair to an object, ensuring that the key is added to the object at a certain order, specified by index
*
* for example:
* ```ts
* const object = { x: true, y: true, z: true }
* const newObject = addKeyToObjectAtKeyIndex({ object, index: 1, key: 'a', value: true });
* // newObject = { x: true, a: true, y: true, z: true }
* ```
*/
const addKeyToObjectAtKeyIndex = ({
object,
index: requestedNewKeyIndex,
key,
value,
}: {
object: Record<string, any>;
index: number;
key: string;
value: any;
}) => {
return Object.keys(object).reduce((newObject, thisKey, thisKeyIndex) => {
if (thisKeyIndex === requestedNewKeyIndex) newObject[key] = value; // add the new key if its the index that was requested
newObject[thisKey] = object[thisKey]; // now add the key that used to be at this index
return newObject; // and continue
}, {} as Record<string, any>);
};
Note: as of ES6, order in which keys were added to an object can matter: https://stackoverflow.com/a/30919039/3068233