Sergino
Sergino

Reputation: 10818

What is the most elegant way of partly copying object arrays in JavaScript

I have two arrays of objects. arrayOne contain items type of myObject1:

var myObject1 = {
  Id: 1, //key
  params: { weight: 52, price: 100 },
  name: "",
  role: ""
};

arrayTwo contained items type of myObject2:

var myObject2 = {
      Id: 1, //key
      name: "real name",
      role: "real role"
    };

I want to copy all names and roles from arrayTwo to arrayOne. id is the key, both arrays contains myObjects with that is mached by 'id`.

Upvotes: 2

Views: 95

Answers (2)

That Guy
That Guy

Reputation: 379

A solution that runs in linear time.

var arrayOne; 	// Array containing objects of type myObject1
var arrayTwo; 	// Array containing objects of type myObject2
var tempObj = {};

// Transform arrayOne to help achieve a better performing code
arrayOne.forEach(function(obj){
	tempObj[obj.id] = obj;
});

// Runs on linear time O(arrayTwo.length)
arrayTwo.forEach(function(obj){
	// Note, since I'm not adding any thing to the arrayTwo
	// I can modify it in this scope
	var match = tempObj[obj.id];
	
	if(match){
		// If a match is found
		obj.name = match.name;
		obj.role = match.role;
	}
});

Upvotes: 1

Roamer-1888
Roamer-1888

Reputation: 19288

If the two arrays are guaranteed to be congruent, then with the use of jQuery.extend(), the code is trivial :

$.each(arrayOne, function(i, obj) {
    $.extend(obj, arrayTwo[i]);
});

Upvotes: 2

Related Questions