matenji
matenji

Reputation: 365

Loop over a reference object multiple times to copy its properties to other objects in Javascript/Angularjs

Let's say I have an array of objects called arr1:

[{a:1, b:2, c:3, type:1}, {c:1, type:2}, {d:1, e:2, type:2}]

The objects in it share a property called 'type' with other objects in the array arr2:

[{d:1, e:2, type:1}, {a:1, b:2, type:2}]

How can I refer to the 'type' property to copy arr2's remaining properties into arr1? The desired result would be:

[{a:1, b:2, c:3, d:1, e:2 type:1}, {a:1, b:2, c:1, type:2}, {a:1, b:2, d:1, e:2, type:2}]

When I use something like angular.extend([], arr1, arr2), it only copies arr2's properties into the first 2 objects in arr1 (the 3rd object doesn't get love). What am I missing? Advanced thanks to all.

Upvotes: 1

Views: 243

Answers (1)

Austin Greco
Austin Greco

Reputation: 33544

Try this:

I'm using functions only available in newer browsers, so if you need to support old ones, you'll have to look into polyfills or use a library.

var a = [{a:1, b:2, c:3, type:1}, {c:1, type:2}, {d:1, e:2, type:2}];
var b = [{d:1, e:2, type:1}, {a:1, b:2, type:2}];

// get an array of all types -- [1, 2, 2]
var types = a.map(function(o) {
  return o.type
});
// filter it down to unique types -- [1, 2]
types = types.filter(function(type, i) {
  return i === types.indexOf(type);
});

var list = [];

// loop through first array
angular.forEach(a, function(o) {
  // get all objects that match type: x
  var matches = b.filter(function(match) {
    return o.type === match.type;
  });

  matches.unshift({});
  matches.unshift(o);
  // merge all matches into object from first array
  var merged = angular.extend.apply(this, matches);

  list.push(merged);
});

console.log(list)

document.getElementById('output').innerHTML = JSON.stringify(list);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<pre id="output"></pre>

Upvotes: 1

Related Questions