假设我们有以下数据条目:



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
    }
  }
];





我不知道这些对象键在等级内,因此对象也可能像这样:



{
  "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键的maxrating值:



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);

09-25 19:10