Qix
0
Q:

how to add field to object in js

var data = {
    'PropertyA': 1,
    'PropertyB': 2,
    'PropertyC': 3
};

data["PropertyD"] = 4;

// dialog box with 4 in it
alert(data.PropertyD);
alert(data["PropertyD"]);
7
let yourObject = {};

//Examples:
//Example 1
let yourKeyVariable = "yourKey";
yourObject[yourKeyVariable] = "yourValue";

//Example 2
yourObject["yourKey"] = "yourValue";

//Example 3
yourObject.yourKey = "yourValue";
2
// 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" }
6
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});
8

New to Communities?

Join the community