add key value pair to object code example
Example 1: how to add field to object in js
// original object { key1: "a", key2: "b"}
var obj = {
key1: "a",
key2: "b"
};
// adding new filed - you can use 2 ways
obj.key3 = "c"; // static
// or
obj["key3"] = "c"; // dynamic - 'key3' can be a variable
console.log(obj) // {key1: "a", key2: "b", key3: "c" }
Example 2: add key value pair to all objects in array
var arrOfObj = [{
name: 'eve'
}, {
name: 'john'
}, {
name: 'jane'
}];
var result = arrOfObj.map(function(el) {
var o = Object.assign({}, el);
o.isActive = true;
return o;
})
console.log(arrOfObj);
console.log(result);
Example 3: add new key value pair to object javascript
const person = {
name: "Elon Musk"
}
person.age = 49;
console.log(person);
// {name: "Elon Musk", age: 49}
Example 4: js add data in object
var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);