简体   繁体   中英

Merging javascript arrays

I have an array like this:

[
  32545343: {
    data: [{id: 1}, {id: 2}]
  },
  547347: {
    data: [{id: 1}, {id: 4}]
  },
  95757: {
    data: [{id: 1}, {id: 6}]
  },
]

How can I merge all data array in a single array without duplicating objects with the same id, like this:

[{id: 1}, {id: 2}, {id: 4}, {id: 6}]

Solution with using Set structure

 var d = { 32545343: { data: [{ id: 1 }, { id: 2 }] }, 547347: { data: [{ id: 1 }, { id: 4 }] }, 95757: { data: [{ id: 1 }, { id: 6 }] }, }; var set = new Set(); Object.keys(d).forEach(a => d[a].data.forEach(b => set.add(JSON.stringify(b)))); document.write(Array.from(set)); 

Assuming, you have an object, then this solution would work with a temoprary object for collecting same object.

 var data = { 32545343: { data: [{ id: 1 }, { id: 2 }] }, 547347: { data: [{ id: 1 }, { id: 4 }] }, 95757: { data: [{ id: 1 }, { id: 6 }] } }, result = function (object) { var r = []; Object.keys(object).forEach(function (k) { object[k].data.forEach(function (a) { if (!this[a.id]) { this[a.id] = a; r.push(a); } }, this); }, {}); return r; }(data); document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>'); 

The question is not correct, you cannot define array like a map: [ x: 1, y:1 ], correct definition:

var a = {
  32545343: {
    data: [{id: 1}, {id: 2}]
  },
  547347: {
    data: [{id: 1}, {id: 4}]
  },
  95757: {
    data: [{id: 1}, {id: 6}]
  }
};

one solution is using a flatmap (one implementation is here: https://gist.github.com/samgiles/762ee337dff48623e729 )

Array.prototype.flatMap = function(lambda) { 
    return Array.prototype.concat.apply([], this.map(lambda)); 
};

then you can convert (do not forget a is not an array it is an object!)

var b = Object.keys(a).flatMap(function(key) { return a[key].data; });

// than you can distinct the list:

var result = b.filter(function(element, index, arr) { return arr.slice(index+1).filter(function(e) { return e.id === element.id }).length===0; });
console.log(result);

You could adopt a functional approach where you pick out unique objects from a flattened array created from each object's data array.

function flatten(arr) {
  return arr.reduce(function (p, c) {
    return p.concat(c);
  }, []);
}

function pluck(obj, key) {
  return Object.keys(obj).map(function (el) {
    return obj[el][key];
  });
}

function unique(arr, key) {
  var ids = [];
  return arr.filter(function (el) {
    if (ids.indexOf(el[key]) === -1) {
      ids.push(el[key]);
      return true;
    }
  });
}

var result = unique(flatten(pluck(obj, 'data')), 'id');

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM