Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert key value pair at certain position in an object of javascript

Tags:

javascript

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"}
like image 228
saurabh kumar Avatar asked Mar 06 '19 06:03

saurabh kumar


2 Answers

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"}
like image 83
tsu Avatar answered Oct 11 '22 10:10

tsu


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)

like image 24
Mayur Patil Avatar answered Oct 11 '22 12:10

Mayur Patil