user3186206
user3186206

Reputation:

How do you copy properties of an object into another without adding properties using Javascript or jQuery?

I want to copy the right object into the left object without copy properties that are in the right object into the left. In the end, I only want the properties that exist in the left object. I can use JavaScript and jQuery

var left = { "id": "123" };
var right = { "id": "456", "no": "false" };

$.each(left, function (l1_key, l1Value) {
  if (typeof l1Value === 'object') {
    const left_l2 = left[l1_key];
    const right_l1_properties = right[l1_key]; 
    $.each(left_l2, function (l2_key, l2Value) {
      l2Value = right_l1_properties[l2_key];
    });
  }
});

left need to be:

{ "id": "456" };

Upvotes: 0

Views: 63

Answers (2)

user2560539
user2560539

Reputation:

You could use Object.getOwnPropertyNames() on left and Array.forEach to iterate over the array of left properties. That way you could exclude properties from right that don't match. The complete logic is implemented in the snippet below.

function changeMatchingProps(left, right) {
if (typeof left === 'object' && typeof right === 'object') {
Object.getOwnPropertyNames(left).forEach(function (val, idx, array) {
    if(right.hasOwnProperty(val)) {
          left[val] = right[val];
    }
});
}
}
var left = { "id": "123" };
var right = { "id": "456", "no": "false" };
changeMatchingProps(left, right);
console.log(left);
var left = { "id": "123", "no": "false", "yes": "true" };
var right = { "id": "456", "no": "true" };
changeMatchingProps(left, right);
console.log(left);
var left = { "id": "123", "pid": "" };
var right = { "id": "456", "no": "false", "pid": "afd39cb123df" };
changeMatchingProps(left, right);
console.log(left);
var left = { "id": "123" };
var right = {};
changeMatchingProps(left, right);
console.log(left);

Upvotes: 0

Snowmonkey
Snowmonkey

Reputation: 3761

Simply iterate over all properties in the left object, check if that key exists in the right object, and set the left keyed value to the right keyed value.

var left = { "id": "123" }; var right = { "id": "456", "no": "false" };

for (var prop in left){
  if(prop in right) {
    left[prop] = right[prop];
  }
};

console.log(left);

No jQuery needed.

EDIT: rather than using if(right[prop]), it does make more sense to be a little more object-happy and use either hasOwnProperty or in to check for the existence of the matching property in right. I've updated the code to use in. A discussion on in vs hasOwnProperty.

Upvotes: 2

Related Questions