add new element to object code example
Example 1: 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)
var addToObject = function (obj, key, value, index) {
var temp = {};
var i = 0;
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
if (i === index && key && value) {
temp[key] = value;
}
temp[prop] = obj[prop];
i++;
}
}
if (!index && key && value) {
temp[key] = value;
}
return temp;
};
var lunch = {
sandwich: 'turkey',
drink: 'soda',
chips: true
};
var lunchWithDessert = addToObject(lunch, 'dessert', 'cookie');
var lunchWithTopping = addToObject(lunch, 'topping', 'tomato', 1);
var lunchClone = addToObject(lunch);
let obj = {b: 1, c: 3};
let c = Object.assign({b: null , a: 5, c: null}, obj);
console.log(c);
Example 2: javascript add to object
var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);
var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push({element: element});
Example 3: js add data in object
var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);