问题描述
我有一组分组对象,但我无法迭代并达到预期的结果。
var cmdLineVal = System.getProperty("java.util.logging.loglevel");
if (cmdLineVal != null) {
LogManager.getLogManager().updateConfiguration(
(key) -> (oldVal,newVal) -> {
if (key.equals(".level")
|| key.equals(ConsoleHandler.class.getName() + ".level")) {
return cmdLineVal;
}
return newVal;
}
);
}
我想消除所有可能的重复项并将所有相似的对象按如下方式分组
[ 000000010: [
{
"userId" : "000000010","played" : 10,"lost" : 5,"date" :"2019-04-01T00:00:00.000Z"
},{
"userId" : "000000010","played": 15,"lost" : 0,"date" :"2019-04-02T00:00:00.000Z"
},],000000020: [
{
"userId" : "000000020","played": 11,"lost" : 4,{
"userId" : "000000020",]
]
我试过了
{
"userId" : "000000010","played": 30,},"played": 26,"lost" : 6,
但它回来了
Object.entries()
我也试过
[obeject: object]
但我没有定义
解决方法
如果您要对 played
和 lost
字段求和,您应该使用 reduce
来合并对象,对所需字段求和。然后将条目数组转换回对象。
试试这个
const inputData = {
"000000010":[
{
"userId":"000000010","played":10,"lost":5,"date":"2019-04-01T00:00:00.000Z"
},{
"userId":"000000010","played":15,"lost":0,"date":"2019-04-02T00:00:00.000Z"
}
],"000000020":[
{
"userId":"000000020","played":11,"lost":4,{
"userId":"000000020","date":"2019-04-02T00:00:00.000Z"
}
]
};
const result = Object.entries(inputData).map(([key,values]) => {
const merged = values.reduce((accum,x) => {
accum.played += x.played;
accum.lost += x.lost;
return accum;
},{"userId": key,"played": 0,"lost": 0});
return [key,merged];
});
console.log(Object.fromEntries(result));
节点打印以下内容
{
'000000010': { userId: '000000010',played: 25,lost: 5 },'000000020': { userId: '000000020',played: 26,lost: 4 }
}
,
我已经更正了 json 数据格式并制作了此代码。以下代码不会删除 key
date
。请告诉我这是否适合您。
function removeDuplicates() {
// Create an array of objects
var movies = [{
"000000010": [{
"userId": "000000010","played": 10,"lost": 5,"date": "2019-04-01T00:00:00.000Z"
},{
"userId": "000000010","played": 15,"lost": 0,"date": "2019-04-02T00:00:00.000Z"
},]
},{
"000000020": [{
"userId": "000000020","played": 11,"lost": 4,{
"userId": "000000020",]
}
];
jsonObject = movies.map(JSON.stringify);
uniqueSet = new Set(jsonObject);
uniqueArray = Array.from(uniqueSet).map(JSON.parse);
console.log(uniqueArray);
}
<p>
Click on the button to remove the duplicated in the array
</p>
<p>Check the console for the output</p>
<button onclick="removeDuplicates();">
Click here
</button>