首页 > 解决方案 > 在 Nodejs 中读取 API 数据并创建对象

问题描述

我的API回报低于nodejs.

console.log(body)打印以下内容。

{
  "items": [
    {
      "PlanId": 2007,
      "PlanCode": "Future Mat Cost Planning  - Budget",
      "Description": "Future Mat Cost Planning  - Budget",
      "FromMonth": "2019-10-01T00:00:00+00:00"
    },
    {
      "PlanId": 3001,
      "PlanCode": "Nvidia Cost PL",
      "Description": "Nvidia Cost PL",
      "FromMonth": "2019-10-01T00:00:00+00:00"

    },
    {
      "PlanId": 1001,
      "PlanCode": "Material Cost Planning - PO",
      "Description": "Material Cost Planning - PO",
      "FromMonth": "2019-10-01T00:00:00+00:00"
    }
   ],
 "count": 5,
  "hasMore": true,
  "limit": 5,
  "offset": 0
}

我必须创建我必须在其中存储PlanIdplancode. 我怎样才能做到这一点。我需要以键值格式存储数据。谁能帮我创建数组或对象?我是nodejs的新手,我想要这样的结果。

obj=[{
      "PlanId": 3001,
      "PlanCode": "Nvidia Cost PL",
     },
    {
      "PlanId": 1001,
      "PlanCode": "Material Cost Planning - PO",
    }
    ];

标签: javascriptnode.jsarrays

解决方案


所以你想map响应一个新对象?

// assuming `body` is the API response

const obj = body
  .items
  .map(item => ({
    PlanId: item.PlanId,
    PlanCode: item.PlanCode,
  });

推荐阅读