showing results for - "how to add a property at the middle of an object in javascript"
Philipp
14 Mar 2019
1
2// Main Code Using Function:
3
4var addToObject = function (obj, key, value, index) {
5
6	// Create a temp object and index variable
7	var temp = {};
8	var i = 0;
9
10	// Loop through the original object
11	for (var prop in obj) {
12		if (obj.hasOwnProperty(prop)) {
13
14			// If the indexes match, add the new item
15			if (i === index && key && value) {
16				temp[key] = value;
17			}
18
19			// Add the current item in the loop to the temp obj
20			temp[prop] = obj[prop];
21
22			// Increase the count
23			i++;
24
25		}
26	}
27
28	// If no index, add to the end
29	if (!index && key && value) {
30		temp[key] = value;
31	}
32
33	return temp;
34
35};
36
37
38// Output:
39
40// Original object
41var lunch = {
42  sandwich: 'turkey',
43  drink: 'soda',
44  chips: true
45};
46
47// Add to the end of the object
48var lunchWithDessert = addToObject(lunch, 'dessert', 'cookie');
49
50// Add between sandwich and drink
51var lunchWithTopping = addToObject(lunch, 'topping', 'tomato', 1);
52
53// Immutable copy of lunch
54var lunchClone = addToObject(lunch);
55
56
57// In Normal Way: ( For simple work )
58
59// let obj = {b: 1, c: 3};
60// let c = Object.assign({b: null , a: 5, c: null}, obj);
61// console.log(c);
62
63// let obj = {"1" : "test1","2" : "test2"};
64// let c = Object.assign({"key1": "value1"}, obj);
65// console.log(c);
66// console.log(c['1']);  //in that case not happening, new property added to the end
Mandy
11 Oct 2018
1let obj = {'b': 2, 'c': 3};
2Object.assign({a: 1}, obj);
3
4// Object {a: 1, b: 2, c: 3}