jeudi 7 mai 2020

Find min(max) value amoung all object.properties and return result as object or (modify original object)

This a bit easy task at first look, with finding the min/max values in Object, has become a challenge for me.

I have the following object (with 3 fixed keys):

let object_ = {
    vendor: 5, //(Number),
    market: 2, //(Number)
    derivative: {
        price: 15 //(Number)
    }
}

And I am trying to find not just the min/max value, but return it as an object / modify the original one, which should looks like that:

result for min: //as an object

{ market: 2}

result for max: //as an object

derivative: {
    price: 15 //(Number)
}

As for now, I have the following code which solves this problem by creating an Array from original object's properties (by manually checking each property's name), like:

/** Create an array of objects from object_*/

let array = [
   {market: 2},
   {vendor: 5},
   {derivative: 15}
]

/** Find the necessary values in array with map and reduce*/

And then finding min/max values from all objects inside array, but the problem is that I should convert result of my code back to the original schema like:

if (resultObject.property === 'derivative') {
   resultObject.derivative = {
      price: resultObject.derivative  //15
   }
}

So the question is:

Am I on the right path, should I create an Array of objects for this case? Cause it's important for me, return not just the number itself, but with a custom named property.

Maybe someone has more better/shorter solution with ES6 syntax or modifying the original object with delete not min (or max) properties. Or can point me a way in to it?

Aucun commentaire:

Enregistrer un commentaire