从具有多个属性的数组映射json数据

问题描述 投票:1回答:1

我有以下json对象

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"
            }
          }
        }
      }
    }

}
}

而且我需要将值从json对象映射到javascript数组

例如

MyArray = [

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

},

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

我需要映射两个值,每个实例的key => label(例如“ cust.created.v1”)和每个实例的summery => Description

我试图用map来做,但是我很难用键和内部属性来做,是否可以用map来做?

javascript node.js json typescript lodash
1个回答
0
投票

Object.entries是您问题的关键;)

Object.entries(obj.topics).map(topic => ({
    Label: topic[0],
    Description: topic[1].subscribe.summary
}))

0
投票

获取对象的entries,然后将其映射:

Object.entries(obj.topics).map(([k,v])=>({Label:k, Description:v.subscribe.summary}))
© www.soinside.com 2019 - 2024. All rights reserved.