2

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"}
  • 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

5 Answers5

4

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"}
moqiyuanshi
  • 524
  • 3
  • 17
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
  • 260,466
  • 31
  • 181
  • 209
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,321
  • 1
  • 13
  • 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

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
  • 32,967
  • 5
  • 31
  • 51
0

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
  • 50
  • 1
  • 8