英文:
Get multiple JSON values from search in JS
问题
console.log(event.pos[0]['$'].a, event.pos[0]['$'].x, event.pos[0]['$'].z);
英文:
I need to loop thru json data looking for a keyword. Once found I need to pull 3 values to my console.log
This is for a Node.js project. The json is a local file.
How the data is laid out.
{
"eventposdef": {
"event": [
{
"$": {
"name": "FIND THIS"
},
"pos": [
{
"$": {
"a": "THIS VALUE 1",
"x": "THIS VALUE 2",
"z": "THIS VALUE 3"
}
},
]
}
Ive tried the following but it only returns the name.
// result is the entire file loaded. The below code does get part of the inquiry
var json = result;
json.eventposdef.event.forEach(event => {
if (event["$"].name === var2){
console.log(event.name) //returns the name
console.log(event.pos) // returns nothing
console.log(event.pos.a) //returns nothing
}
})
I expect to return...
"a" THIS VALUE 1
"x" THIS VALUE 2
"z" THIS VALUE 3
答案1
得分: 0
我不确定您是要按事件名称筛选还是打印所有位置,但您可以使用Object.keys(pos.$)来获取对象的所有属性并将它们打印到控制台上。这是我的参考代码,我跳过了null和undefined的检查条件。
const data = {
"eventposdef": {
"event": [
{
"$": {
"name": "FIND THIS"
},
"pos": [
{
"$": {
"a": "THIS VALUE 1",
"x": "THIS VALUE 2",
"z": "THIS VALUE 3"
}
},
]
}
]
}
};
// 遍历事件
data.eventposdef.event.forEach(event => {
// 检查事件名称是否是我们想要的
if (event.$.name !== 'FIND THIS') {
return;
}
event.pos.forEach(pos => {
Object.keys(pos.$).forEach(key => {
console.log(`"${key}" ${pos.$[key]}`);
});
});
});
这段代码会遍历事件,检查事件名称是否为“FIND THIS”,然后遍历位置属性并将它们打印到控制台上。
英文:
I'm not sure if you want to filter by event name or print all pos, but you can use Object.keys(pos.$) to get all the properties of an object and print them to the console. This is my reference code, I skipped null and undefined check conditions.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const data = {
"eventposdef": {
"event": [
{
"$": {
"name": "FIND THIS"
},
"pos": [
{
"$": {
"a": "THIS VALUE 1",
"x": "THIS VALUE 2",
"z": "THIS VALUE 3"
}
},
]
}]}};
// Loop through the events
data.eventposdef.event.forEach(event => {
// Check if the event name is the one we want
if (event.$.name !== 'FIND THIS') {
return;
}
event.pos.forEach(pos => {
Object.keys(pos.$).forEach(key => {
console.log(`"${key}" ${pos.$[key]}`);
});
});
});
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论