Search code examples
javascriptangular6angular7angular8

Trying to create the request for API and technology in Angular 7


i want that if we are getting the masterColumn in an object then array should be formed with the name of that mastercolumn's value and desc value should be pushed in that formed array. In the second object if we get same mastercolumn's value then no array should be formed and only desc value should be pushed in already present array, but if we get different masterColumn's value then with that value new array should be formed and the desc value of object should be pushed in the newly formed array. If masterColumn is absent from an object then nothing should happen.

**  input from api[
{
columnType: "bool"
desc: "postscandata1"
masterColumn: "Sensor Data"},
{
columnType: "bool",
desc: "postscandata2",
masterColumn: "Sensor Data"
},
{
columnType: "bool",
desc: "postscandata3",
masterColumn: "Sensor"
},
]
required Output
"jsonColumnName": {
                "Sensor Data": ["postscandata1", "postscandata2"]
                "Sensor": ["postscandata3"]
            },```

Solution

  • You can do something like that, it can be improved for sure:

    const result = {};
    
    for (const item of json) {
      if (result[item.masterColumn]) {
        result[item.masterColumn].push(item.desc);
      } else {
        result[item.masterColumn] = [item.desc];
      }
    }
    

    the output:

    {"Sensor Data":["postscandata1","postscandata2"],"Sensor":["postscandata3"]}