skip to Main Content

Let’s say I have a JSON file like so (char_table.json):

{
  "char_285_medic2": {
    "name": "Lancet-2",
    "description": "Restores the HP of allies and ignores the Deployment Limit, but has a long Redeployment Time",
    "canUseGeneralPotentialItem": false,
    "canUseActivityPotentialItem": false
   },
"char_291_aglina": {
    "name": "Angelina",
    "description": "Deals Arts damage and Slows the target for a short time",
    "canUseGeneralPotentialItem": true,
    "canUseActivityPotentialItem": false
   },
"char_2013_cerber": {
    "name": "Ceobe",
    "description": "Deals Arts damage",
    "canUseGeneralPotentialItem": true,
    "canUseActivityPotentialItem": false,
   },
   ...
}

I currently only have the "name" varible, and I want to find the path of the object containing that exact "name" (example: name = "Angelina" would return char_table.char_291_aglina | name = "Ceobe" would return char_table.char_2013_cerber). How can I exactly do that using javascript?

2

Answers


  1. Try this recursive re-usable function

    1. Read the json file from a path and convert into js object
    const fs = require('fs')
    
    const readJSONFromFile = filePath => {
      try {
        const jsonData = fs.readFileSync(filePath, 'utf-8');
        return JSON.parse(jsonData);
      } catch (error) {
        console.error(`Error reading JSON file: ${error.message}`);
        return null;
      }
    }
    
    1. Find the node by property name and the value of that property using recursion function
    const findObjectNodeByPropertyAndValue = (obj, targetProperty, targetValue, currentPath = '') => {
      for (const key in obj) {
        if (typeof obj[key] === 'object') {
          const newPath = currentPath ? `${currentPath}.${key}` : key;
          if (obj[key][targetProperty] === targetValue) {
            return newPath;
          } else {
            const result = findObjectNodeByPropertyAndValue(obj[key], targetProperty, targetValue, newPath);
            if (result) {
              return result;
            }
          }
        }
      }
      return null;
    }
    

    Usage:

    const filePath = '<YOUR-JSON-PATH>.json'
    const charData = readJSONFromFile(filePath);
    if(charData) {
      const node = `${filePath.split(".json")[0]}.${findObjectNodeByPropertyAndValue(charData, 'name', 'Angelina')}`;
      console.log(node)
    }
    
    Login or Signup to reply.
  2. const char_table = require("./char_table.json");
    
    function getKeyFromName(askedName) {
      for ([key, value] of Object.entries(char_table)) {
        if (value.name.includes(askedName)) return key;
      }
    }
    console.log("result", getKeyFromName("Ceobe")); // char_2013_cerber
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search