如何将键值对集合作为 JSON 数组进行访问

我正在对核心 3.1 中的 ASP.NET 页面进行 Ajax 调用。


响应是 其属性是自定义类的实例,其本身包含各种字符串和集合属性。JsonResultValue


其中一个集合是 ,然后我可以在 JavaScript 中按以下行访问它:Dictionary<string, string>


var dictionary = response.DictionaryObj;


for (key in dictionary) {

    DoSomeStuff(key, dictionary[key]);

}

然而,这些集合中的另一个需要一个非唯一的“密钥”,并且目前是一个List<KeyValuePair>


这最终在JavaScript中作为一个对象数组,我可以像这样访问它:


var kvps = response.KvpList;


for (i = 0; i < kvps.length; i++) {

   var kvp = kvps[i];

   DoSomeMoreStuff(kvp.key, kvp.value);

}

后者似乎远没有那么优雅 - 有没有办法以一种允许我使用前一种语法的方式打包KeyValuePairs?


PIPIONE
浏览 80回答 2
2回答

胡子哥哥

因为你可以使用对象条目()Dictionary<string, string>对于对象解构List<KeyValuePair>const dictionaryObj = {&nbsp; &nbsp; a: 'somestring',&nbsp; &nbsp; b: 42,};for (const [key, value] of Object.entries(dictionaryObj)) {&nbsp; &nbsp; console.log(`${key}: ${value}`); // DoSomeStuff(key, value)}console.log('===========================================');const kvpList = [&nbsp; &nbsp; { key: '1', value: 'v1' },&nbsp; &nbsp; { key: '2', value: 'v2' },&nbsp; &nbsp; { key: '3', value: 'v3' },];for (const { key, value } of kvpList) {&nbsp; &nbsp; console.log(`${key}: ${value}`); // DoSomeMoreStuff(key, value)}

杨__羊羊

如果你有一个对象,并且你想迭代它的属性,那么我们可以使用方法来获取给定对象自己的可枚举字符串键控属性[key,value]对的数组,然后只使用循环:Object.entriesforeachlet input =&nbsp; { "workType": "NDB To Nice", "priority": 5, "name": "Joseph", "lastName": "Skeet" }const fooFunctiion = (key, value) => {&nbsp; console.log(`key: ${key}, value ${value}` )}Object.entries(input).forEach(([k, v]) => {&nbsp; &nbsp; fooFunctiion(k, v)});如果你有一个对象数组,那么你可以使用方法:foreachlet input = [&nbsp; { "workType": "NDB To Nice", "priority": 5 },&nbsp; { "workType": "PDAD", "priority": 0 },&nbsp; { "workType": "PPACA", "priority": 0 },&nbsp; { "workType": "Retrigger", "priority": "5" },&nbsp; { "workType": "Special Intake Request Intake", "priority": "7" }];const fooFunction = (obj, index) => {&nbsp; console.log('obj: ', obj, index )}input.forEach((obj, ind) =>&nbsp; &nbsp; fooFunction(obj, ind));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript