How to add a new item to an object at a specific position with vanilla JS
How to add a new item to an object at a specific position with JS:
t.ly/uWcQ *** (using function)
// https://gomakethings.com/how-to-add-a-new-item-to-an-object-at-a-specific-position-with-vanilla-js/
// 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:
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
How to add a new item to an object at a specific position with JS:
t.ly/uWcQ *** (using function)
// https://gomakethings.com/how-to-add-a-new-item-to-an-object-at-a-specific-position-with-vanilla-js/
// In Normal Way:
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