Gutelaunetyp
Gutelaunetyp

Reputation: 1882

Build min and max dynamically with keys

Let's assume we have the following data entries:

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

I don't know these object keys within rating, so the object could also look like:

{
  "id": "1",
  "name": {
    "first": "",
    "last": ""
  },
  "nickname": "test2",
  "rating": {
    "ab": 28,
    "cd": 26,
    "moep": 27,
    "bla": 14
  }
}

I would like to do the following:

So the result should look like this:

{
  kw: {
    min: 1,
    max: 28
  },
  dc: {
    min: 2,
    max: 26
  },
  imp: {
    min: 3,
    max: 27
  },
  pat: {
    min: 1,
    max: 14
  },

}

How can I achieve this ?

Upvotes: 1

Views: 43

Answers (2)

adiga
adiga

Reputation: 35222

You could reduce the array. Loop through the keys of rating and set the min and max for each key

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 output = data.reduce((acc, { rating }) => {
  for (const key in rating) {
    const value = rating[key];
    acc[key] = acc[key] || { min: value, max: value }; // if key doesn't exist, add it
    acc[key].min = Math.min( acc[key].min, value )
    acc[key].max = Math.max( acc[key].max, value )
  }

  return acc;
}, {})

console.log(output)

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 191976

You can reduce the array, and use Array.forEach() to iterate the entries, and create/populate the min and max values of each rating key:

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

Upvotes: 1

Related Questions