7

I have a javascript object which consists of key-value pairs, I want to insert a key-value pair at a certain location, In the below example I want to insert it after the first key-value pair.

var obj = {key1: "value1", key2: "value2"};

console.log(obj);// {key1: "value1", key2: "value2"}

obj.key3 = "value3";

console.log(obj);// {key1: "value1", key2: "value2", key3: "value3"}
saurabh kumar
  • 83
  • 1
  • 5
  • you might want to take a look at the answer here https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order, you cannot choose the order of keys – Ovidiu Dolha Mar 06 '19 at 06:35
  • choose your data structure wisely. – AZ_ Mar 06 '19 at 06:42

6 Answers6

13

For add key value after certain index, We can use Object.entries() and Object.fromEntries().

let obj = {key1: "value1", key2: "value2"};
let keyValues = Object.entries(obj); //convert object to keyValues ["key1", "value1"] ["key2", "value2"]
keyValues.splice(1,0, ["newKey","newValue"]); // insert key value at the index you want like 1.
let newObj = Object.fromEntries(keyValues) // convert key values to obj {key1: "value1", newKey: "newValue", key2: "value2"}
tsu
  • 1,122
  • 1
  • 10
  • 22
4

For ES5

There is no guarantee of order in Javascript objects. You just add new key value like obj.key3 = "value3"; and key3 will be available on obj.

For ES6


function insertKey(key,value,obj,pos){
  return Object.keys(obj).reduce((ac,a,i) => {
    if(i === pos) ac[key] = value;
    ac[a] = obj[a]; 
    return ac;
  },{})
}


data = insertKey('key3','value3',data,1);
console.log(data)

Mayur Patil
  • 120
  • 2
  • 8
1

In ES6+ environments, in which non-numeric properties are iterated over in insertion order, delete the key2 first, then add it back in after setting key3:

var obj = {key1: "value1", key2: "value2"};
const { key2 } = obj;
delete obj.key2;
obj.key3 = "value3";
obj.key2 = key2;
console.log(obj);

Still, this is a pretty odd thing to try to do, and isn't guaranteed to work in ES5. You might consider using an array instead.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

You can create a function for this purpose and use reduce() on Object.keys

var data = {key1: "value1", key2: "value2"};

function insertKey(key,value,obj,pos){
  return Object.keys(obj).reduce((ac,a,i) => {
    if(i === pos) ac[key] = value;
    ac[a] = obj[a]; 
    return ac;
  },{})
}


data = insertKey('key3','value3',data,1);
console.log(data)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

Object properties in JavaScript have no defined order. There is no guarantee that the order in which you define them in your object literal will mean anything anywhere else.

Some good info

Kai
  • 2,529
  • 1
  • 15
  • 24
  • 1
    This is not true as of ES6 and beyond, which most modern browsers run on. – CertainPerformance Mar 06 '19 at 06:37
  • @CertainPerformance true, with some caveats, but I would argue that depending on the order of properties is a bad idea and that someone finding themself in such a situation should take a step back and have a hard look at why they need to do this – Kai Mar 06 '19 at 06:40
  • Quite often the reason for wanting a specific order is for generating a human-readable format such as XML, where it can be helpful to have keys in a particular order to make editing easier from the human side. – Clonkex Mar 04 '21 at 23:16
  • @Clonkex of course there's a use case for ordering elements in a collection. And for that, a different data structure should be used – Kai Mar 04 '21 at 23:22
  • @Kai Perhaps, but I've never seen a XML or JSON generator that _used_ a different data structure. For that reason and others it's completely reasonable to want to control the order of properties on an object. – Clonkex Mar 05 '21 at 00:06
0

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

Ulad Kasach
  • 11,558
  • 11
  • 61
  • 87