How to add a property at the middle of an object in javascript code example
Example 1: How to add a property at the middle of an object in javascript
// Main Code Using Function:
var addToObject = function (obj, key, value, index) {
// Create a temp object and index variable
var temp = {};
var i = 0;
// Loop through the original object
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
// If the indexes match, add the new item
if (i === index && key && value) {
temp[key] = value;
}
// Add the current item in the loop to the temp obj
temp[prop] = obj[prop];
// Increase the count
i++;
}
}
// If no index, add to the end
if (!index && key && value) {
temp[key] = value;
}
return temp;
};
// Output:
// Original object
var lunch = {
sandwich: 'turkey',
drink: 'soda',
chips: true
};
// Add to the end of the object
var lunchWithDessert = addToObject(lunch, 'dessert', 'cookie');
// Add between sandwich and drink
var lunchWithTopping = addToObject(lunch, 'topping', 'tomato', 1);
// Immutable copy of lunch
var lunchClone = addToObject(lunch);
// In Normal Way: ( For simple work )
// let obj = {b: 1, c: 3};
// let c = Object.assign({b: null , a: 5, c: null}, obj);
// console.log(c);
// let obj = {"1" : "test1","2" : "test2"};
// let c = Object.assign({"key1": "value1"}, obj);
// console.log(c);
// console.log(c['1']); //in that case not happening, new property added to the end
Example 2: add key vakue to front of object
let obj = {'b': 2, 'c': 3};
Object.assign({a: 1}, obj);
// Object {a: 1, b: 2, c: 3}