2

I have an array :

[{name:'blah',id:1},{name:'blah2',id:3}]

I have another array :

[{type:'blah',uid:3435},{type:'blah2',uid:3}]

I want to end up with :

[{newname:'blah2',uidid:3}]

You can see I want to match the two based on a mapping of id=uid. Really struggling to find a way to do this in js. I have underscore installed.

Exitos
  • 29,230
  • 38
  • 123
  • 178
  • PHPJS allows you with the functions `array_combine()` and `array_intersection()`. Long live phpjs! – Marcos Pérez Gude Jun 21 '16 at 16:05
  • You want to match based on `id` and `uid`? – thefourtheye Jun 21 '16 at 16:06
  • yes if this was PHP – Exitos Jun 21 '16 at 16:06
  • 3
    `ar1.filter(item1 => ar2.some(item2 => item2.uid===item1.id))` – Touffy Jun 21 '16 at 16:08
  • And you want to change the field names as well? – thefourtheye Jun 21 '16 at 16:10
  • what is the likelihood you'd switch to lodash over underscore? Compelling reasons to consider this - http://stackoverflow.com/questions/13789618/differences-between-lodash-and-underscore – jusopi Jun 21 '16 at 16:22
  • I'm struggling to understand why you are struggling. Are you struggling to come up with the thought process? Are you struggling to write a loop over array elements? Are you struggling with finding an object's properties? Are you struggling with how to build the resulting array? –  Jun 21 '16 at 16:24

2 Answers2

1

Since you are wanting an array with an object that uses different key names, something like this will work. It is also simple to read and to understand without any complex syntax or logic.

var arr1 = [{name: 'blah', id: 1}, {name: 'blah2', id: 3}];
var arr2 = [{type: 'blah', uid: 3435}, {type: 'blah2', uid: 3}];

var arr3 = [];

arr1.forEach(function(obj1, i) {
  arr2.forEach(function(obj2) {
    if (obj1.id == obj2.uid) {
      arr3.push({newname: obj1.name, uidid: obj1.id})
    }
  })
});

console.log(arr3);
KevBot
  • 17,900
  • 5
  • 50
  • 68
  • This was the right answer but I learned a little more from Ninas as I always wondered how hash maps work. – Exitos Sep 27 '16 at 08:27
1

You could build a hash table with the first array and use it in the iteration of the second array.

var array1 = [{ name: 'blah', id: 1 }, { name: 'blah2', id: 3 }],
    array2 = [{ type: 'blah', uid: 3435 }, { type: 'blah2', uid: 3 }],
    hash = Object.create(null),
    match = [];

array1.forEach(function (a) {
    hash[a.id] = a;
});

array2.forEach(function (a) {
    hash[a.uid] && match.push({ newname: a.type, uidid: a.uid });
});

console.log(match);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392