[英]Group list of objects by JSON key
I am trying to reformat my list of objects by grouping a certain key pair in javascript.我正在尝试通过在 javascript 中对某个密钥对进行分组来重新格式化我的对象列表。
Data Format数据格式
[{
"sccode": "sccode1",
"val": "1ADA"
}, {
"sccode": "sccode2",
"val": "1ADB"
}, {
"sccode": "sccode1",
"val": "1ADC"
}]
Expected Result预期结果
[{
"scCode": "sccode1",
"valCodes": ["1ADA", "1ADC"]
},
{
"scCode": "sccode2",
"valCodes": ["1ADB"]
}
]
I believe I could loop through the array and match my keys, but is there a quick way to reformat this without having to explicitly loop through?我相信我可以遍历数组并匹配我的键,但是有没有一种快速的方法来重新格式化它而不必显式遍历? I've tried using a reduce function below, but it gives undefined errors with find, which i think has something to do with my formatting.我试过使用下面的 reduce 函数,但它在 find 中给出了未定义的错误,我认为这与我的格式有关。
Tried (?) Code尝试(?)代码
const resp = data.reduce((acc, ele) => {
const ant = acc.find(x => x.sccode === ele.sccode);
}, []);
Would this do?这行吗?
const src = [{"sccode":"sccode1","val":"1ADA"},{"sccode":"sccode2","val":"1ADB"},{"sccode":"sccode1","val":"1ADC"}], result = src.reduce((r,{sccode,val}) => { const match = r.find(({scCode}) => scCode == sccode) match ? match.valCodes.push(val) : r.push({scCode:sccode, valCodes: [val]}) return r }, []) console.log(result)
.as-console-wrapper{min-height:100%;}
Try the following, I use a map to store a partial state to improve performances preventing to search sccode in an array for every initial object.尝试以下操作,我使用映射来存储部分状态以提高性能,从而防止在数组中为每个初始对象搜索 sccode。
let partial = [{
"sccode": "sccode1",
"val": "1ADA"
}, {
"sccode": "sccode2",
"val": "1ADB"
}, {
"sccode": "sccode1",
"val": "1ADC"
}].reduce((map, obj) => {
if (!map[obj.sccode]) {
map[obj.sccode] = [obj.val];
} else {
map[obj.sccode].push(obj.val);
}
return map;
}, {})
Object.keys(partial).map(sccode => ({
sccode, valCodes: partial[sccode]
}));
try loaddash/groupby试试 loaddash/groupby
let groupByResult = groupBy(data, function (n) {
return n.sccode
});
Check this code:检查此代码:
array.reduce(function(res, value){
if(!res[value.sccode]) {
res[value.sccode] = value;
res[value.sccode]['valCodes'] = []
result.push(res[value.sccode]);
}
res[value.sccode]['valCodes'].push(value.val);
return res;
} ,{});
I tested here and it works fine!我在这里测试过,效果很好!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.