8

Like in arrays we can add new elements by using array.push(item). How to do the same with objects? And can it be done inside the object? Like:

var myObject={apple: "a", orange: "o"};
var anothObject = {lemon: "l", myObject};
Rana Mallah
  • 167
  • 1
  • 1
  • 9

7 Answers7

10

To copy all elements of one object to another object, use Object.assign:

var myObject = { apple: "a", orange: "o" };
var anothObject = Object.assign( { lemon: "l" }, myObject );

Or, more elegantly ES6 style using spread ... operator:

let myObject = { apple: "a", orange: "o" };
let anothObject = { lemon: "l", ...myObject };
Frido Emans
  • 5,120
  • 2
  • 27
  • 42
7

You could add some properties of an object simply like this :

obj = {a : "1", b : "2"};

myObj = {c: "3", d : "4"};
myObj.a = obj.a;
myObj.b = obj.b;

Update:

In that case just do this :

for(var prop in obj) myObj[prop] = obj[prop];

And to filter out the unwanted properties inside the loop body you could also do this :

for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
        myObj[prop] = obj[prop];
    }
}
vjdhama
  • 4,878
  • 5
  • 33
  • 47
3

You can use jQuery's extend function: http://api.jquery.com/jquery.extend/

var object1 = {
  apple: 0,
  banana: { weight: 52, price: 100 },
  cherry: 97
};
var object2 = {
  banana: { price: 200 },
  durian: 100
};

// Merge object2 into object1
$.extend( object1, object2 );
Jonathan.Brink
  • 23,757
  • 20
  • 73
  • 115
1

A non-jquery option: you could iterate of the keys of the object to be merged.

var myObject={apple: "a", orange: "o"};
var anothObject = {lemon: "l"};

Object.keys(myObject).forEach(function(key) {
    anothObject[key] = myObject[key];
});

At the end of the loop anothObject is {lemon: "l", apple: "a", orange: "o"}

ZygD
  • 22,092
  • 39
  • 79
  • 102
Olivia O.
  • 11
  • 1
0
var myObject={apple: "a", orange: "o"};
myObject.lemon = 1; // myObject is now {apple: "a", orange: "o", lemon: 1}
Trott
  • 66,479
  • 23
  • 173
  • 212
0
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;

};
Omprakash Patel
  • 532
  • 4
  • 15
-1

You can use jQuery.extend() function

var myObject={apple: "a", orange: "o"};
var anothObject = {lemon: "l"};

jQuery.extend(myObject, anothObject);
console.log(myObject);
Adem İlhan
  • 1,460
  • 3
  • 16
  • 26