Home > Enterprise >  Reading a non static key from a JSON file in Javascript
Reading a non static key from a JSON file in Javascript

Time:09-30

I'm trying to read the current profile of a user from an API, but the problem is that I would not known the profile id, since it is randomly generated. Is there a way to maybe skip this key and check which object has current set to true, or maybe another way?

Any help is appreciated.

{
    "profiles": {
        "70560fe0cdce4e9b91a0a161a257e188": {
            "profile_id": "70560fe0cdce4e9b91a0a161a257e188",
            "cute_name": "Pomegranate",
            "current": true,
            "last_save": 1632932207555,
            "raw": {},
            "items": {},
            "data": {}
        },
        "b49bab4a08a64be38edec3f9ecf8f639": {
            "profile_id": "b49bab4a08a64be38edec3f9ecf8f639",
            "cute_name": "Raspberry",
            "current": false,
            "last_save": 1630180158660,
            "raw": {},
            "items": {},
            "data": {}
        }
    }
}

CodePudding user response:

If you're using modern JS you can filter the objects to find what you need.

const obj = {
  "profiles": {
    "70560fe0cdce4e9b91a0a161a257e188": {
      "profile_id": "70560fe0cdce4e9b91a0a161a257e188",
      "cute_name": "Pomegranate",
      "current": true,
      "last_save": 1632932207555,
      "raw": {},
      "items": {},
      "data": {}
    },
    "b49bab4a08a64be38edec3f9ecf8f639": {
      "profile_id": "b49bab4a08a64be38edec3f9ecf8f639",
      "cute_name": "Raspberry",
      "current": false,
      "last_save": 1630180158660,
      "raw": {},
      "items": {},
      "data": {}
    }
  }
}

const profiles = Object.values(obj.profiles) // convert to useable array

console.log(profiles.filter(p => p.current === true))

CodePudding user response:

const data = {
    "profiles": {
        ...
    }
}

for (const [key, value] of Object.entries(data.profiles)) {
  if (value.current) {
      console.log(`${key} is true`);
  }
}

Output: 70560fe0cdce4e9b91a0a161a257e188 is true

That could be an easy approach to work with the data

CodePudding user response:

You can loop through an object's enumerable properties, such as these, without needing to know their keys by using a for...in loop.

Otherwise, depending on what browsers you have to support, you could use Object.values to convert an object into an array of its enumerable values, and you could then run Array.prototype.filter.

Here's a brief example using a for...in loop, assuming your API response is saved in a data variable:

let activeProfiles = [];

for (let profileId in data.profiles) {
    let profile = data.profiles[profileId];
    if (profile.current === true) {
        activeProfiles.push(profile);
    }
}

And if you wanted to use the Object.values method, something like this should do the trick:

const activeProfiles = Object.values(data.profiles).filter((profile) => profile.current === true);
  • Related