Convert flat array of objects into nested array of objects

前端 未结 3 1630
一生所求
一生所求 2021-02-04 07:00

Original JSON data (flat table):

[
    {\"id\":\"1\",\"first_name\":\"Jason\",\"last_name\":\"Martin\",\"start_date\":\"1996-07-25\",\"end_date\":\"2006-07-25\",         


        
3条回答
  •  难免孤独
    2021-02-04 07:28

    You might take a look at the nest() operator from D3.js: https://github.com/mbostock/d3/blob/48ad44fdeef32b518c6271bb99a9aed376c1a1d6/src/arrays/nest.js This is part of D3, a larger library, but looking quickly at the code I just linked to, I don't think this has any dependencies, so you should be able to lift the code here for use in your own project. Usage is described here in the docs - you chain .key() methods to define the keys for each layer of the nested structure. In your case, this might look like:

    data = d3.nest()
        .key(function(d) { return d.city })
        .key(function(d) { return d.description })
        .entries(data);
    

    The structure this spits out is a little different from what you have, but it's functionally quite similar:

    [
      {
        "key": "Toronto", 
        "values": [
          {
            "key": "Programmer", 
            "values": [
              {
                "active": "1", 
                "city": "Toronto", 
                "department": "Finance", 
                "description": "Programmer", 
                "end_date": "2006-07-25", 
                "first_name": "Jason", 
                "id": "1", 
                "last_name": "Martin", 
                "salary": "1234.56", 
                "start_date": "1996-07-25"
              },
              // etc ...
            ]
          }
        ]
      },
      // etc ...
    ]
    

提交回复
热议问题