Search code examples
javascriptarraysjsonasp.net-corekeyvaluepair

How to access KeyValuePair collection as JSON array


I'm making Ajax calls to a page in ASP.NET Core 3.1.

The response is a JsonResult whose Value property is an instance of a custom class, itself containing various string and collection properties.

One of these collections is a Dictionary<string, string>, which I can then access in JavaScript along the following lines:

var dictionary = response.DictionaryObj;

for (key in dictionary) {
    DoSomeStuff(key, dictionary[key]);
}

However another of these collections requires a non-unique 'key', and is currently a List<KeyValuePair>

This ends up in JavaScript as an array of objects, which I can access like this:

var kvps = response.KvpList;

for (i = 0; i < kvps.length; i++) {
   var kvp = kvps[i];
   DoSomeMoreStuff(kvp.key, kvp.value);
}

The latter seems far less elegant - is there a way of packaging up the KeyValuePairs in a way that would let me use the former syntax?


Solution

  • If you have an object and you want to iterate through its properties, then we can use Object.entries method to get an array of a given object's own enumerable string-keyed property [key, value] pairs, and then just use loop foreach:

    let input =  { "workType": "NDB To Nice", "priority": 5, "name": "Joseph", "lastName": "Skeet" }
    
    
    const fooFunctiion = (key, value) => {
      console.log(`key: ${key}, value ${value}` )
    }
    
    Object.entries(input).forEach(([k, v]) => {
        fooFunctiion(k, v)
    });

    If you have an array of objects, then you can use foreach method:

    let input = [
      { "workType": "NDB To Nice", "priority": 5 },
      { "workType": "PDAD", "priority": 0 },
      { "workType": "PPACA", "priority": 0 },
      { "workType": "Retrigger", "priority": "5" },
      { "workType": "Special Intake Request Intake", "priority": "7" }
    ];
    
    const fooFunction = (obj, index) => {
      console.log('obj: ', obj, index )
    }
    
    input.forEach((obj, ind) =>
        fooFunction(obj, ind)
    );