javascriptlinqlinq.js

Convert array of employees to Dictionary


So I'm using the LinqJS library to currently achieve the following:

    var allEmployees = [
        {
            "Id": 1374,
            "FirstName": "John",
            "LastName": "Doe"
        },
        {
            "Id": 1375,
            "FirstName": "Jane",
            "LastName": "Doe"
        }
    ];
    var employeeDictionary = Enumerable.from(allEmployees).toDictionary("$.Id", "$.FirstName+' '+$.LastName").toEnumerable().toArray();

When serializing employeeDictionary to JSON, I get the following format:

[
  {
    "key": 1374,
    "value": "John Doe"
  },
  {
    "key": 1375,
    "value": "Jane Doe"
  }
]

I do not want my data in this format, I wish to have it in this format:

{
  "1374": "John Doe",
  "1375": "Jane Doe"
}

I wrote something similar in PHP using YaLinqo which gives me the results I need:

echo json_encode(from($employees)->toDictionary('$v["Id"]', '$v["FirstName"]." ".$v["LastName"]')->toArray());

However, I would like to be able to achieve this in my JavaScript.


Solution

  • In JavaScript, an array is strictly always numerically indexed structure. So, .toArray abides with that. In PHP an array is closer to what JavaScript considers plain objects.


    If using this LINQ JavaScript library

    You can use the .toObject method to produce an object of your format - you need to pass in two functions - a key selector and a value selector, so the object gets built with the correct data:

    var allEmployees = [
        {
            "Id": 1374,
            "FirstName": "John",
            "LastName": "Doe"
        },
        {
            "Id": 1375,
            "FirstName": "Jane",
            "LastName": "Doe"
        }
    ];
    var employeeDictionary = Enumerable.from(allEmployees)
      .toDictionary("$.Id", "$.FirstName+' '+$.LastName")
      .toEnumerable()
      .toObject(entry => entry.key, entry => entry.value);
    
    /* output:
    {
      "1374": "John Doe",
      "1375": "Jane Doe"
    }
    */
    

    Using destructuring, the key/value selectors can be transformed to:

    .toObject(({key}) => key, ({value}) => value);
    

    If using this library for LINQ operations, then you need to slightly change the syntax:

    var allEmployees = [
        {
            "Id": 1374,
            "FirstName": "John",
            "LastName": "Doe"
        },
        {
            "Id": 1375,
            "FirstName": "Jane",
            "LastName": "Doe"
        }
    ];
    var employeeDictionary = Enumerable.From(allEmployees)
      .ToDictionary("$.Id", "$.FirstName+' '+$.LastName")
      .ToEnumerable()
      .ToObject("$.Key", "$.Value");
    
    /* output:
    {
      "1374": "John Doe",
      "1375": "Jane Doe"
    }
    */