Home > OS >  Get values from multidimensional object to list
Get values from multidimensional object to list

Time:09-11

I have object:

data = {
    "usa": {
        "a": {
            "min": 1,
            "max": 2,
            "avg": 1.5
        },
        "b": {
            "min": 3,
            "max": 5,
            "avg": 4
        }
    },
    "canada": {
        "c": {
            "min": 1,
            "max": 2,
            "avg": 1.5
        }
    }
}

I would like receive all max values from second dimension, for example:

function getMaxValues(country: string): number[] {
    const maxValues: number[] = data[country]???

    return maxValues;
}

I any better way than iterate over this object and collect results? In other languages are special functions for this. I don't want use iteration because this object is very large and usually specific functions for this are more efficient.

CodePudding user response:

You need to get the country object values then map to get max value.

let data = {
    "usa": {
        "a": {
            "min": 1,
            "max": 2,
            "avg": 1.5
        },
        "b": {
            "min": 3,
            "max": 5,
            "avg": 4
        }
    },
    "canada": {
        "c": {
            "min": 1,
            "max": 2,
            "avg": 1.5
        }
    }
}

function getMaxValues(country) {
    const maxValues = Object.values(data[country]).map(v => v.max);

    return maxValues;
}

console.log(getMaxValues('usa'));

CodePudding user response:

You can do:

Object.values(data).flatMap((country) => {
   return Object.values(country).map(({max}) => max);
});

CodePudding user response:

You can reduce the entries of the object:

const data = {
    "usa": {
        "a": {
            "min": 1,
            "max": 2,
            "avg": 1.5
        },
        "b": {
            "min": 3,
            "max": 5,
            "avg": 4
        }
    },
    "canada": {
        "c": {
            "min": 1,
            "max": 2,
            "avg": 1.5
        }
    }
};

const maxValuesPerCountry = Object.entries(data)
  .reduce( (acc, [key, value]) => 
    ( {...acc, [key]: Object.entries(value).map(([, v]) => v.max) } ), {} );

console.log(maxValuesPerCountry);
.as-console-wrapper {
    max-height: 100% !important;
}

  • Related