使用JavaScript获取JSON中值的路径

huangapple go评论67阅读模式
英文:

Getting the path of a value in JSON using javascript

问题

我目前只有"name"变量,并且我想找到包含确切"name"的对象的路径(例如:name = "Angelina"将返回char_table.char_291_aglina | name = "Ceobe"将返回char_table.char_2013_cerber)。如何在JavaScript中精确执行这个操作?

英文:

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?

答案1

得分: 1

使用Object.keys()方法从char_table对象获取键的数组,然后使用Array.find()方法搜索与指定名称的字符对应的键。如果找到匹配的键,它将被返回;否则,它将返回null

function findCharacterKeyByName(char_table, name) {
    return Object.keys(char_table).find((key) => char_table[key].name === name) || null;
}

const char_table = {
    char_291_aglina: {
        name: "Angelina",
        description: "Deals Arts damage",
        canUseGeneralPotentialItem: true,
        canUseActivityPotentialItem: false,
    },
    char_2013_cerber: {
        name: "Ceobe",
        description: "Deals Arts damage",
        canUseGeneralPotentialItem: true,
        canUseActivityPotentialItem: false,
    },
};

const nameToFind = "Angelina";
const characterKeyFound = findCharacterKeyByName(char_table, nameToFind);

if (characterKeyFound) {
    console.log("Character Found: " + characterKeyFound);
} else {
    console.log("Character Not Found!");
}
英文:

Use the Object.keys() method to get an array of keys from the char_table object, and then the Array.find() method to search for a key that corresponds to a character with the specified name. If a matching key is found, it is returned; otherwise, it returns null.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

function findCharacterKeyByName(char_table, name) {
    return Object.keys(char_table).find((key) =&gt; char_table[key].name === name) || null;
}

const char_table = {
    char_291_aglina: {
        name: &quot;Angelina&quot;,
        description: &quot;Deals Arts damage&quot;,
        canUseGeneralPotentialItem: true,
        canUseActivityPotentialItem: false,
    },
    char_2013_cerber: {
        name: &quot;Ceobe&quot;,
        description: &quot;Deals Arts damage&quot;,
        canUseGeneralPotentialItem: true,
        canUseActivityPotentialItem: false,
    },
};

const nameToFind = &quot;Angelina&quot;;
const characterKeyFound = findCharacterKeyByName(char_table, nameToFind);

if (characterKeyFound) {
    console.log(&quot;Character Found: &quot; + characterKeyFound);
} else {
    console.log(&quot;Character Not Found!&quot;);
}

<!-- end snippet -->

答案2

得分: 0

尝试使用这个可递归重用的函数:

  1. 从路径中读取 JSON 文件并转换为 JavaScript 对象
const fs = require('fs')

const readJSONFromFile = filePath => {
  try {
    const jsonData = fs.readFileSync(filePath, 'utf-8');
    return JSON.parse(jsonData);
  } catch (error) {
    console.error(`读取 JSON 文件时发生错误:${error.message}`);
    return null;
  }
}
  1. 使用递归函数按属性名称和属性值查找节点
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;
}

用法:

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)
}
英文:

Try this recursive re-usable function

  1. Read the json file from a path and convert into js object
const fs = require(&#39;fs&#39;)

const readJSONFromFile = filePath =&gt; {
  try {
    const jsonData = fs.readFileSync(filePath, &#39;utf-8&#39;);
    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 = &#39;&#39;) =&gt; {
  for (const key in obj) {
    if (typeof obj[key] === &#39;object&#39;) {
      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 = &#39;&lt;YOUR-JSON-PATH&gt;.json&#39;
const charData = readJSONFromFile(filePath);
if(charData) {
  const node = `${filePath.split(&quot;.json&quot;)[0]}.${findObjectNodeByPropertyAndValue(charData, &#39;name&#39;, &#39;Angelina&#39;)}`;
  console.log(node)
}

答案3

得分: 0

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
英文:
const char_table = require(&quot;./char_table.json&quot;);

function getKeyFromName(askedName) {
  for ([key, value] of Object.entries(char_table)) {
    if (value.name.includes(askedName)) return key;
  }
}
console.log(&quot;result&quot;, getKeyFromName(&quot;Ceobe&quot;)); // char_2013_cerber

huangapple
  • 本文由 发表于 2023年7月23日 18:44:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76747809.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定