How to Push Key-Value Pair Into an Array Using Javascript?
how to push key value pair to object javascript
var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);
// Array of Objects in form {element: {id: 10, quantity: 10} }
var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push({element: element});
We can only use this function if the function has only one statement.
The map() method makes a new array by calling a function once for every array’s element. It does not modify the original array and run for empty elements.
var arr1 = ['left', 'top'];
const arr2 = arr1.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});
console.log(arr2);
Output
{
left: 0,
top: 0
}
left: 0,
top: 0
}