Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/422.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将行转换为列json_Javascript_Arrays_Json - Fatal编程技术网

Javascript 如何将行转换为列json

Javascript 如何将行转换为列json,javascript,arrays,json,Javascript,Arrays,Json,我有一个json对象数组,希望将行转换为列,并将旁边的列转换为列的值。这就像postgresql的函数交叉表 json是这样的: {"marketcode":"01","size":"8,5","amount":1}, {"marketcode":"01","size":"9","amount":1}, {"marketcode":"01","size":"10","amount":0}, {"marketcode": "01", "8,5": 1, "9": 1, "10": 0} 我希望

我有一个json对象数组,希望将行转换为列,并将旁边的列转换为列的值。这就像postgresql的函数交叉表

json是这样的:

{"marketcode":"01","size":"8,5","amount":1},
{"marketcode":"01","size":"9","amount":1},
{"marketcode":"01","size":"10","amount":0},
{"marketcode": "01", "8,5": 1, "9": 1, "10": 0}
我希望它是这样的:

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

我搜索了一些lodash,但没有找到任何东西

希望这就是您要找的:

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()];
};

小提琴手:

非常感谢比尔,很抱歉提出了一个愚蠢的问题,但我认为这个问题有一个lib,我也编写了一个解决方案,不管怎样,非常感谢,按照我的代码:

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";
   }        
  }         
 });
});

小提琴:

你好,布鲁诺!到目前为止你试过什么?某种循环?我们可以查看您的代码吗?可能重复的可能重复的您正在尝试按marketcode属性分组吗?