ashermcoa ashermcoa - 7 months ago 10
Javascript Question

Transform JavaScript array using key/code

I need help with a function that can transform array A to array B in JavaScript

Array A:

[ { id: 'U125H069G', code: 'C13LKL4V6' },
{ id: 'U13MPMLA3', code: 'C13LKL4V6' },
{ id: 'U125H069G', code: 'C125H083C' },
{ id: 'U13MPMLA3', code: 'C125H083C' },
{ id: 'U125H069G', code: 'C123Q00D9' },
{ id: 'U13MPMLA3', code: 'C123Q00D9' },
{ id: 'U125H069G', code: 'C13LM1VUP' } ]


Array B:

[{'id':'U125H069G', codes: ['C13LKL4V6','C125H083C','C123Q00D9', 'C13LM1VUP]},
{'id':'U13MPMLA3': codes: ['C13LKL4V6','C125H083C','C123Q00D9']}]

Answer

Your designed object should be

{'id':'U125H069G', codes: ['C13LKL4V6','C125H083C','C123Q00D9', 'C13LM1VUP']}

instead of

{'id':'U125H069G', codes: {'C13LKL4V6','C125H083C','C123Q00D9', 'C13LM1VUP'}}

Try like this

var temp = [];

data.forEach(function(x) {
  if (temp.map(function(y) {
      return y.id
    }).indexOf(x.id) < 0) {
    var codes = data.filter(function(z) {
      return z.id == x.id;
    }).map(function(z) {
      return z.code;
    });
    temp.push({
      id: x.id,
      codes: codes
    });
  }
})

console.log(temp);

DEMO

Comments