我有一个数组json对象,并且想要将行转换为列,并将侧面的列转换为column的值。就像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}


我搜索了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()];
};


小提琴:https://jsfiddle.net/cccheng118/pyh2L85k/6/

关于javascript - 如何将行转换为列json,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57114000/

10-09 17:31