gpt4 book ai didi

javascript - 如何在迭代中获取 json 名称值而不是索引或 id?

转载 作者:行者123 更新时间:2023-12-03 06:16:45 25 4
gpt4 key购买 nike

我有以下 json:

var testjson = {
"Mytest": [{
"Testing": {
"static": {
"name": "first name"
},
"key1": "key1 val",
"key2": 10

}
}, {
"Testing": {
"static": {
"name": "second name"
},
"key3": 20,
"key4": true


}
}, {
"Testing": {
"static": {
"name": "third name"
},
"key5": "key5 val"

}
}]
}

我有以下coffeescript: @itemNames = (item for item of @mydata).sort (a,b) -> a>b ,但我将其更改为以下javascript转换:

var mydata = testjson.Mytest;
var item;

this.itemNames = ((function() {
var results;
results = [];
for (item in mydata) {
results.push(item);
}
return results;
}).call(this)).sort(function(a, b) {
return a > b;
});
console.log(mydata);//gives: [Object, Object, Object]
console.log(this.itemNames);//gives: ["0", "1", "2"], but I need it like: ["first name", "second name", "third name"], how can I get it ?

在这里,我在控制台中得到的输出为:["0", "1", "2"],但我需要这样的输出:["first name", “第二个名字”,“第三个名字”],当然,如果我在控制台上展开它,它应该显示这些值(例如:0:“名字”,1:“第二个名字” ,2:“第三个名字”)。创建Fiddle .

请帮助我了解如何获取这些名称并提前致谢。

最佳答案

你可以这样做。你的项目是元素的索引。你需要获取索引处的元素,然后通过 Testing.static.name< 访问属性 name/.

this.itemNames = ((function() {
var results;
results = [];
for (item in mydata) {
results.push(mydata[item].Testing.static.name);
}
return results;
}).call(this)).sort(function(a, b) {
return a > b;
});

这是代码。

var testjson = {
"Mytest": [{
"Testing": {
"static": {
"name": "first name"
},
"key1": "key1 val",
"key2": 10

}
}, {
"Testing": {
"static": {
"name": "second name"
},
"key3": 20,
"key4": true


}
}, {
"Testing": {
"static": {
"name": "third name"
},
"key5": "key5 val"

}
}]
};


var mydata = testjson.Mytest;
var item;

this.itemNames = ((function() {
var results;
results = [];
for (item in mydata) {
results.push(mydata[item].Testing.static.name);
}
return results;
}).call(this)).sort(function(a, b) {
return a > b;
});

console.log(this.itemNames);

关于javascript - 如何在迭代中获取 json 名称值而不是索引或 id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39072137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com