英文:
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) => 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!");
}
<!-- end snippet -->
答案2
得分: 0
尝试使用这个可递归重用的函数:
- 从路径中读取 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;
}
}
- 使用递归函数按属性名称和属性值查找节点
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
- 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;
}
}
- 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)
}
答案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("./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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论