首页 > 解决方案 > 如何从 api 响应中迭代复杂对象

问题描述

这是一个 api 响应,我想从响应中迭代所有appIduserInfo。我如何迭代这个响应?

{
    "status_code": "SUCCESS",
    "status": "SUCCESS",
    "message": "Success",
    "data": [
        {
            "_id": "6034acaaf751f1c89721a76b",
            "status": "active",
            "name": "testname",
            "collectionStatus": "completed",
            "createdDate": 1614064810201,
            "subscriberStats": [],
            "platforms": [
                {
                    "_id": "6034acaa47a83e45b3f5fc4a",
                    "status": "active",
                    "traffic": 0,
                    "parentStatus": "active",
                    "platformType": "website",
                    "appId": "xxx",
                    "optinShowInterval": 0,
                    "optInFrequencyType": "page_refresh",
                    "webType": "wordpress",
                    "optInFrequency": 0,
                    "userId": "xxx",
                    "createdDate": 1614064810563
                }
            ]
        },
        {
            "_id": "600ae310255964c2e21a580f",
            "status": "active",
            "name": "trial",
            "collectionStatus": "completed",
            "createdDate": 1611326224761,
            "subscriberStats": [],
            "platforms": [
                {
                    "_id": "600ae31163d6d321f4693d1d",
                    "status": "active",
                    "traffic": 0,
                    "parentStatus": "active",
                    "platformType": "website",
                    "webType": "wordpress",
                    "appId": "xxx",
                    "optinShowInterval": 0,
                    "optInFrequencyType": "page_refresh",
                    "optInFrequency": 0,
                    "userId": "xxx",
                    "createdDate": 1611326225013
                }
            ]
        }
    ]
}

结果输出应该是一个对象数组,例如:

[
   {appId: "", userInfo: ""},
   {appId: "", userInfo: ""}
]

标签: javascriptnode.jsjsonapijavascript-objects

解决方案


尝试添加一些循环:

const result = [];
for (const a in response) {
  for (const b of response[a]) {
    result.push({
      appId: b._id,
      userInfo: b.parentStatus // or some other properties
    })
  }
}

console.log(result)

推荐阅读