0

I have a array json objects, and want convert the rows to columns and the column at side as value of column. It's like the function crosstab of postgresql

the json it's like this:

{"marketcode":"01","size":"8,5","amount":1},
{"marketcode":"01","size":"9","amount":1},
{"marketcode":"01","size":"10","amount":0},

I want it's like this:

{"marketcode": "01", "8,5": 1, "9": 1, "10": 0}

I searched for something lodash, but i did not find anything

  • Hi Bruno! What have you tried so far? Some sort of loop? Can we see your code? – Matt Ellen Jul 19 '19 at 13:57
  • Possible duplicate of [convert/flatten array of objects](https://stackoverflow.com/questions/8514716/convert-flatten-array-of-objects) – Matt Ellen Jul 19 '19 at 14:00
  • Possible duplicate of [How can I access and process nested objects, arrays or JSON?](https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json) – Liam Jul 19 '19 at 14:00
  • are you trying to group by marketcode property ? – Kunal Mukherjee Jul 19 '19 at 14:29

2 Answers2

1

Hope this is what you are looking for:

const convert = toConvert => {
    const map = toConvert.reduce((r, {marketcode, size, amount}) => {
    if (r.has(marketcode))
        r.set(marketcode, {...r.get(marketcode), [size]: amount});
     else
        r.set(marketcode, {marketcode, [size]: amount});
    return r;
  }, new Map());
  return [...map.values()];
};

fiddle: https://jsfiddle.net/cccheng118/pyh2L85k/6/

Bill Cheng
  • 926
  • 7
  • 9
0

Thanks very much Bill, sorry for idiot question, but i thinking that had a lib for this problem, i coded one solution too, anyone way, thanks very much, follow my code:

empresas.forEach((e, index) => {
 //coloca empresa no código
 result[index] = {'empresa': e};
 // adiciona as numerações como colunas e a quantidade em estoque como
 // quantidade e nº de vendas se houver
 a.forEach(ia => {
  // checa se a numeração é referente a empresa
   if (result[index].empresa == ia.empresa) {
    if (ia.quantidade !== undefined && ia.vendas !== undefined) {
     result[index][ia.tamanho] = ia.quantidade + '/' + ia.vendas;
    } else {
     result[index][ia.tamanho] = ia.quantidade + '/' + "0";
   }        
  }         
 });
});

fiddle: https://jsfiddle.net/v1hLs5o0/6/