-1

The following code changes the values in an object to new values, but imposes a threshold limit for each property based on a third limits object.

const oldValues = {
  value1: 10,
  value2: 20,
}

const newValues = {
  value1: 1,
  value2: 100,
}

const limits = {
  value1: 20,
  value2: 30,
}

const outputValues = {
  value1: newValues.value1 < limits.value1 ? newValues.value1 : limits.value1,
  value2: newValues.value2 < limits.value2 ? newValues.value2 : limits.value2,
}

// outputs: {value1: 1, value2: 30}

This works fine, but if I add a lot more properties, this code gets very repetitive and cumbersome to read. Is there a cleaner, shorter way to accomplish the same thing?

D-Money
  • 2,375
  • 13
  • 27
  • 1
    Consider using a function? – evolutionxbox Aug 08 '22 at 09:25
  • You can do `oldValues["value1"]` instead, which means you can now put the key in a string variable. Now simply write a function that does the update and pass the key to it as string. –  Aug 08 '22 at 09:25
  • Duplicate: [How can I access and process nested objects, arrays, or JSON?](https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json) –  Aug 08 '22 at 09:25

1 Answers1

1

You can use loops to go over the fields. Your example modified:

const oldValues = {
    value1: 10,
    value2: 20,
}

const newValues = {
    value1: 1,
    value2: 100,
}

const limits = {
    value1: 20,
    value2: 30,
}

const outputValues = {}

for (let key in newValues) {
    outputValues[key] = Math.min(newValues[key], limits[key]);
}

// outputs: {value1: 1, value2: 30}

You can extract it to a method, is up to you how you make it more reusable, if you need.

tenbits
  • 7,568
  • 5
  • 34
  • 53