Search code examples
javascriptnode.jsjsontypescriptlodash

Map json data from array with several properties


I’ve the following json object

https://codebeautify.org/jsonviewer/cb01bb4d

obj = 
{
  "api": "1.0.0",
  "info": {
    "title": "Events",
    "version": "v1",
    "description": "Set of events"
  },
  "topics": {
    "cust.created.v1": {                            //Take this value
      "subscribe": {
        "summary": "Customer Register Event v2",    //Take this value
        "payload": {
          "type": "object",
          "required": [
            "storeUid"

          ],
          "properties": {
            "customerUid": {
              "type": "string",
              "description": "Email of a Customer",
              "title": "Customer uid"
            }
          }
        }
      }
    },
    "qu.orderplaced.v1": {                     //Take this value
      "subscribe": {
        "summary": "Order Placed",             //Take this value
        "payload": {
          "type": "object",
          "required": [
            "quoteCode"
          ],
          "properties": {
            "quoteCode": {
              "type": "string",
              "example": "762",
              "title": "Quote Code"
            }
          }
        }
      }
    } 
  }
}

And I need to map the values from the json objects to javascript array

E.g.:

MyArray = [
 {
   Label: “cust.created.v1”,
   Description:  "Customer Register Event v2"

 },
 {
   Label: “qu.orderplaced.v1”,
   Description: "Order Placed",
 }
]

I need to map the two values, the key => label for each instance (e.g. “cust.created.v1” ) and the summary => Description from each instance

I’ve tried to do it with map but I struggled to do it with key and the property inside, is it possible to do it with map ?


Solution

  • Take entries of object then map it:

    var obj = { "api": "1.0.0", "info": { "title": "Events", "version": "v1", "description": "Set of events" }, "topics": { "cust.created.v1": { "subscribe": { "summary": "Customer Register Event v2", "payload": { "type": "object", "required": [ "storeUid" ], "properties": { "customerUid": { "type": "string", "description": "Email of a Customer", "title": "Customer uid" } } } } }, "qu.orderplaced.v1": { "subscribe": { "summary": "Order Placed", "payload": { "type": "object", "required": [ "quoteCode" ], "properties": { "quoteCode": { "type": "string", "example": "762", "title": "Quote Code" } } } } }}}
    
    var result = Object.entries(obj.topics).map(([k,v])=>({Label:k, Description:v.subscribe.summary}));
    
    console.log(result);