我有一个数组 json 对象,想要将行转换为列,并将旁边的列作为列的值。就像postgresql的函数crosstab
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()];
};
关于javascript - json如何将行转换为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57114000/