push new values into 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: 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)
let obj = {b: 1, c: 3};
let c = Object.assign({b: null , a: 5, c: null}, obj);
console.log(c);