js adding properties to object code example

Example 1: how to add property to object in javascript

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

data["PropertyD"] = 4;

// dialog box with 4 in it
alert(data.PropertyD);
alert(data["PropertyD"]);

Example 2: How to add a property at the middle of an object in javascript

// Main Code Using Function:

var addToObject = function (obj, key, value, index) {

	// Create a temp object and index variable
	var temp = {};
	var i = 0;

	// Loop through the original object
	for (var prop in obj) {
		if (obj.hasOwnProperty(prop)) {

			// If the indexes match, add the new item
			if (i === index && key && value) {
				temp[key] = value;
			}

			// Add the current item in the loop to the temp obj
			temp[prop] = obj[prop];

			// Increase the count
			i++;

		}
	}

	// If no index, add to the end
	if (!index && key && value) {
		temp[key] = value;
	}

	return temp;

};


// Output:

// Original object
var lunch = {
  sandwich: 'turkey',
  drink: 'soda',
  chips: true
};

// Add to the end of the object
var lunchWithDessert = addToObject(lunch, 'dessert', 'cookie');

// Add between sandwich and drink
var lunchWithTopping = addToObject(lunch, 'topping', 'tomato', 1);

// Immutable copy of lunch
var lunchClone = addToObject(lunch);


// In Normal Way: ( For simple work )

// let obj = {b: 1, c: 3};
// let c = Object.assign({b: null , a: 5, c: null}, obj);
// console.log(c);

// let obj = {"1" : "test1","2" : "test2"};
// let c = Object.assign({"key1": "value1"}, obj);
// console.log(c);
// console.log(c['1']);  //in that case not happening, new property added to the end