简体   繁体   English

从多维 object 中获取值到列表

[英]Get values from multidimensional object to list

I have object:我有 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?我有什么比遍历这个 object 并收集结果更好的方法吗? 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.我不想使用迭代,因为这个 object 非常大,通常为此的特定功能更有效。

You can do:你可以做:

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

You need to get the country object values then map to get max value.您需要获取country object values ,然后获取map以获得max

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

You can reduce the entries of the object:您可以减少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); console.log(`usa: ${maxValuesPerCountry.usa}`);
 .as-console-wrapper { max-height: 100%;important; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM