Как сначала объединить свойства объекта, а затем удалить дубликаты в массиве объектов, используя Javascript - PullRequest
0 голосов
/ 07 августа 2020

У меня есть массив объектов:

const arr = [
  { id: 1, name: "test1", quantity:1 },
  { id: 2, name: "test2", quantity:1 },
  { id: 2, name: "test3", quantity:1 },
  { id: 3, name: "test4", quantity:1 },
  { id: 4, name: "test5", quantity:1 },
  { id: 5, name: "test6", quantity:1 },
  { id: 5, name: "test7", quantity:1 },
  { id: 6, name: "test8", quantity:1 }
];

Я хочу сложить количество повторяющихся объектов вместе перед их удалением

Итак, результат:

const arr = [
  { id: 1, name: "test1", quantity:1 },
  { id: 2, name: "test3", quantity:2 },
  { id: 3, name: "test4", quantity:1 },
  { id: 4, name: "test5", quantity:1 },
  { id: 5, name: "test6", quantity:2 },
  { id: 6, name: "test8", quantity:1 }
];

Я видел варианты, в которых удалялись дубликаты с помощью map или reduce, но я не видел ничего, что могло бы сделать то, что я хочу sh красноречиво, без использования слишком большого количества циклов.

I весь день думали о том, как лучше всего sh это сделать, и ничего не нашли, любая помощь будет принята с благодарностью

Ответы [ 3 ]

2 голосов
/ 07 августа 2020

Вы можете использовать сокращение с объектом для хранения элемента с каждым идентификатором.

const arr = [
  { id: 1, name: "test1", quantity:1 },
  { id: 2, name: "test2", quantity:1 },
  { id: 2, name: "test3", quantity:1 },
  { id: 3, name: "test4", quantity:1 },
  { id: 4, name: "test5", quantity:1 },
  { id: 5, name: "test6", quantity:1 },
  { id: 5, name: "test7", quantity:1 },
  { id: 6, name: "test8", quantity:1 }
];
const res = Object.values(
  arr.reduce((acc,curr)=>{
  acc[curr.id] = acc[curr.id] || {...curr, quantity: 0};
  acc[curr.id].quantity += curr.quantity;
  return acc;
  }, {})
);
console.log(res);
0 голосов
/ 07 августа 2020

Использование forEach l oop и построение объекта с агрегированным количеством.

const convert = (arr) => {
  const res = {};
  arr.forEach(({ id, ...rest }) =>
    res[id] ? (res[id].quantity += 1) : (res[id] = { id, ...rest })
  );
  return Object.values(res);
};

const arr = [
  { id: 1, name: "test1", quantity: 1 },
  { id: 2, name: "test2", quantity: 1 },
  { id: 2, name: "test3", quantity: 1 },
  { id: 3, name: "test4", quantity: 1 },
  { id: 4, name: "test5", quantity: 1 },
  { id: 5, name: "test6", quantity: 1 },
  { id: 5, name: "test7", quantity: 1 },
  { id: 6, name: "test8", quantity: 1 },
];

console.log(convert(arr));
0 голосов
/ 07 августа 2020

const arr = [
    { id: 1, name: "test1", quantity: 1 },
    { id: 2, name: "test2", quantity: 1 },
    { id: 2, name: "test3", quantity: 1 },
    { id: 3, name: "test4", quantity: 1 },
    { id: 4, name: "test5", quantity: 1 },
    { id: 5, name: "test6", quantity: 1 },
    { id: 5, name: "test7", quantity: 1 },
    { id: 6, name: "test8", quantity: 1 }
];

var result = arr.reduce(function (r, a) {
    r[a.id] = r[a.id] || { id: a.id, quantity: 0, name: a.name };
    r[a.id].quantity += a.quantity;
    return r;
}, Object.create(null));

console.log(JSON.stringify(result));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...