Link two positions of an object into a single position

Viewed 68

I receive in this way the object

const tests = [
        {id: 0, vencimiento: "231216000000"},
        {id: 0, monto: "99000"},
        {id: 1, vencimiento: "230117000000"},
        {id: 1, monto: "198000"},
        {id: 2, vencimiento: "230217000000"},
        {id: 2, monto: "297000"},
    ];

And I want to combine the positions with the same id

const resultado= [
     {id: 0, vencimiento: "231216000000", monto: "99000"},
     {id: 1, vencimiento: "230117000000", monto: "198000"},                             
     {id: 2, vencimiento: "230217000000", monto: "297000"},
];
3 Answers

You can use Array.prototype.reduce() and return a plain object,
then use Object.values() to get the result you wanted:

const tests = [
    {id: 0, vencimiento: "231216000000"},
    {id: 0, monto: "99000"},
    {id: 1, vencimiento: "230117000000"},
    {id: 1, monto: "198000"},
    {id: 2, vencimiento: "230217000000"},
    {id: 2, monto: "297000"},
];

const res = Object.values(tests.reduce((acc, curr) => {
  if(!acc[curr.id]) {
    acc[curr.id] = {...curr}
  } else {
    acc[curr.id] = {
      ...acc[curr.id],
      ...curr
    }
  }

  return acc;
}, {}));

console.log(res);

Array.prototype.reduce()
Object.values()

Try this:

const tests = [
  { id: 0, vencimiento: "231216000000" },
  { id: 0, monto: "99000" },
  { id: 1, vencimiento: "230117000000" },
  { id: 1, monto: "198000" },
  { id: 2, vencimiento: "230217000000" },
  { id: 2, monto: "297000" },
];

const newTests = []
for (let index = 0; index < tests.length; index += 2) {
  const arr = tests[index]
  const { monto } = tests[index + 1]
  newTests.push({ ...arr, monto })
}

console.log(newTests)
/* OUTPUT
[
  { id: 0, vencimiento: '231216000000', monto: '99000' },
  { id: 1, vencimiento: '230117000000', monto: '198000' },
  { id: 2, vencimiento: '230217000000', monto: '297000' }
]
*/

How it works

You can deconstruct objects by using the { } when declaring the new variable. You can reconstruct it again using the spread operator ... with arr to combine it with monto.

In cases where number of elements is changing reduce function is great choice

tests.reduce((p,n) => {
    if(p.map(t => t.id).includes(n.id)) {
       let i = p.findIndex(t => t.id === n.id);
       p[i] = {...p[i],...n}
       return p;
    } else {
       return [...p,n]
    }
}, [])

Result:

0: {id: 0, vencimiento: "231216000000", monto: "99000"}
1: {id: 1, vencimiento: "230117000000", monto: "198000"}
2: {id: 2, vencimiento: "230217000000", monto: "297000"}
Related