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"}
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"}
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
.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With