ImmutableJS: merge two list of objects, without duplicating them

我们两清 提交于 2020-01-03 19:09:23

问题


Supposing I have the below:

var allFoods = Immutable.List();

var frenchFood = Immutable.List([
  {
  'type': 'french fries',
  'price': 3
  },
  {
    'type': 'petit gateau',
    'price': 40
  },
  {
    'type': 'croissant',
    'price': 20
  },
]);

var fastFood = Immutable.List([
  {
  'type': 'cheeseburger',
  'price': 5
  },
  {
  'type': 'vegan burger',
  'price': 20
  },
  {
  'type': 'french fries',
  'price': 3
  }
]);

I want to merge both lists, in a way that I also remove dupes (in this case, french fries), so the expected result would be:

{
'type': 'french fries', // keep the first french fries
'price': 3
},
{
  'type': 'petit gateau',
  'price': 40
},
{
  'type': 'croissant',
  'price': 20
},
  {
'type': 'cheeseburger',
'price': 5
},
{
'type': 'vegan burger',
'price': 20
}

What I'm trying (doesn't remove dupes):

allFoods = frenchFood.concat(fastFood);
allFoods = allFoods.filter(function(item, pos) {
    return allFoods.indexOf(item) === pos;
});

Which returns arrays merged, but still duplicated.

What am I missing?


回答1:


const allFoods = frenchFood.concat(fastFood.filter((item) =>
   frenchFood.indexOf(item) < 0
));



回答2:


I would use reduce

var result = frenchFood.concat(fastFood).reduce( (reduction, food) =>  { 
if(reduction[food.type]) {
    return reduction;
}  else { 
    return reduction.set([food.type], food);

}  
}, new Immutable.Map()).valueSeq().toList();



回答3:


I would highly encourage you to not nest js objects inside immutable structures. Better to wrap those objects in an Immutable.Map() or do Immutable.fromJS(yourJsObj).

Least amount of code

const results = Immutable.Set(frenchFood).union(Immutable.Set(fastFood));

However @rooftop answer fastest

https://jsperf.com/union-vs-concat-immutable




回答4:


I found a best solution (for me) on medium, link to origin answer is dead: https://medium.com/@justintulk/merging-and-deduplicating-data-arrays-with-array-reduce-efaa4d7ef7b0

const arr1 = [
  { id: 1, name: 'Array 1-1' },
  { id: 2, name: 'Array 1-2' },
  { id: 3, name: 'Array 1-3' }
]
const arr2 = [
  { id: 1, name: 'Array 2-1' },
  { id: 3, name: 'Array 2-3' },
  { id: 4, name: 'Array 2-4' }
]

const mergeArrObjectsUnique = (currentArr, newArr) => {
  let obj = {}

  currentArr.forEach(item => {
    obj[item.id] = item
  })
  
  newArr.forEach(item => {
    obj[item.id] = item
  })
  
  let result = [];
  
  for(let p in obj) {
    if(obj.hasOwnProperty(p))
    result.push(obj[p])
  }

  console.log('result: ', result)
  return result
}

mergeArrObjectsUnique(arr1, arr2)


来源:https://stackoverflow.com/questions/39908169/immutablejs-merge-two-list-of-objects-without-duplicating-them

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!