假设我们有以下数据条目:
const data = [{
"id": "0",
"name": {
"first": "",
"last": ""
},
"nickname": "test",
"rating": {
"kw": 1,
"dc": 2,
"imp": 3,
"pat": 4
}
},
{
"id": "1",
"name": {
"first": "",
"last": ""
},
"nickname": "test2",
"rating": {
"kw": 28,
"dc": 26,
"imp": 27,
"pat": 14
}
},
{
"id": "2",
"name": {
"first": "",
"last": ""
},
"nickname": "test3",
"rating": {
"kw": 11,
"dc": 8,
"imp": 9,
"pat": 1
}
}
];
我不知道 rating 中的这些对象键,所以对象也可能看起来像:
{
"id": "1",
"name": {
"first": "",
"last": ""
},
"nickname": "test2",
"rating": {
"ab": 28,
"cd": 26,
"moep": 27,
"bla": 14
}
}
我想做以下事情:
- 根据数据对象键动态生成一个新对象(因为我不知道它们)
- 为所有这些对象键创建一个子对象 {min: xx, max: xx}
所以结果应该是这样的:
{
kw: {
min: 1,
max: 28
},
dc: {
min: 2,
max: 26
},
imp: {
min: 3,
max: 27
},
pat: {
min: 1,
max: 14
},
}
我怎样才能做到这一点?
最佳答案
您可以减少数组,并使用 Array.forEach()
迭代条目,并创建/填充 min
和 max
每个 rating
键的值:
const data=[{id:"0",name:{first:"",last:""},nickname:"test",rating:{kw:1,dc:2,imp:3,pat:4}},{id:"1",name:{first:"",last:""},nickname:"test2",rating:{kw:28,dc:26,imp:27,pat:14}},{id:"2",name:{first:"",last:""},nickname:"test3",rating:{kw:11,dc:8,imp:9,pat:1}}];
const result = data.reduce((r, { rating }) => {
Object.entries(rating).forEach(([k, v]) => {
if(!r[k]) r[k] = { min: v, max: v }; // if doesn't exist min = max = current value
else if(v < r[k].min) r[k].min = v; // if current value is less than min -> min = current value
else if(v > r[k].max) r[k].max = v; // if current value is more than max -> max = current value
});
return r;
}, {});
console.log(result);
关于javascript - 使用键动态构建最小值和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58736609/