简体   繁体   中英

Accessing objects in typescript and find the highest key and value of it

this.maxObj = {
    "item": {
        "id": 29842,
        "interestName": "Pre-engagement ring",
        "audienceSize": "980460",
        "femaleAge18_24": "22",
        "maleAge18_24": "11",
        "femaleAge25_34": "25",
        "maleAge25_34": "9",
        "femaleAge35_44": "11",
        "maleAge35_44": "2",
        "femaleAge45_54": "7",
        "maleAge45_54": " 1",
        "femaleAge55_64": "6",
        "maleAge55_64": " 1",
        "femaleAge65plus": "5",
        "maleAge65plus": "  0",
        "gendermale": "24.6",
        "genderFemale": "75.4",
        "isActive": true,
        "createdAt": "2021-03-22T07:01:21.000Z",
        "updatedAt": "2021-03-22T07:01:21.000Z",
        "deletedAt": null
    },
    "refIndex": 21534,
    "score": 0.6113547101723916
}

Consider the above object. First, I write an "if condition" on genderMale and genderfemale to compare the values. I find genderfemale is greater. So my question is as follows: if genderFemale is greater I should select all the femaleAge ( femaleAge18_24 , femaleAge25_34 , femaleAge35_44 , femaleAge45_54 , femaleAge55_64 and femaleAge65plus from the object and find the highest among it. If genderMale is greater then it should find the highest value of maleAge . the final answer should be femaleAge25_34: "25" .

Considering your object structure, you can iterate through all keys of your object by using Object.keys() . Doing so, you will be able to compare the key to any substring by using String.indexOf or something similar and add their values to an array. Finally, check everything within that array using Math.max() and you're good to go.

const items = this.maxObj.item;
let arr = [];

Object.keys(items).forEach((key) => {
  if (key.includes(anySubString)) {
    arr.push(items[key]);
  }
});

// Adjust this one. Example is just taken from MDN
// https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Math/max
const max = arr.reduce(function(a, b) {
  return Math.max(a, b);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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