首页 > 解决方案 > 我需要遍历一个复杂的 JSON ARRAY 对象,以便使用带有 Typescript 的 LODASH 仅返回两个项目

问题描述

这是一个复杂的 JSON 对象...

这是一些代码:

    entity: [{entityName: "Nrm", page: 0, pageSize: 241, status: "successfully perfrom: select Operation",…}]
    0: {entityName: "Nrm", page: 0, pageSize: 241, status: "successfully perfrom: select Operation",…}
    entityName: "Nrm"
    page: 0
    pageSize: 241
    rows: [{columns: [{paramName: "country_alpha3_code", paramValue: "PLW", dataType: "String"},…]},…]
    [0 … 99]
    0: {columns: [{paramName: "country_alpha3_code", paramValue: "PLW", dataType: "String"},…]}
    columns: [{paramName: "country_alpha3_code", paramValue: "PLW", dataType: "String"},…]
    0: {paramName: "country_alpha3_code", paramValue: "PLW", dataType: "String"}
    dataType: "String"
    paramName: "country_alpha3_code"
    paramValue: "PLW"
    1: {paramName: "country_name", paramValue: "PALAU", dataType: "String"}
    dataType: "String"
    paramName: "country_name"
    paramValue: "PALAU"
    2: {paramName: "country_alpha2_code", paramValue: "PW", dataType: "String"}
    dataType: "String"
    paramName: "country_alpha2_code"
    paramValue: "PW"

以下是脚本片段的外观:

在此处输入图像描述

我想要的是一个国家下拉列表的简单 JSON 对象,不,他们不会构建自定义 API 来执行此操作,所以我在 Typescript 和 Lodash 中进行

countries = {
  [{
      name: "United States",
      code: "US"
  },{
      name: "Canada",
      code: "CN"
  },{
      name: "Italy",
      code: "IT"
  },
  ....]

}

而已。

这是我的打字稿函数,我想在其中制作新的 JSON 对象

async getCountryOptions() {
  // this.services.getCountries();
  const response = await this.services.getCountries();

  // console.log('RESPONSE AFTER AWAIT: ', response);
  
  this.countries = this.services.countryList;

  console.log('Did we get countries: ', this.countries);

  // Now to make a new array for only country code and name
  ****************** HERE *********************


  // I TRIED THIS but I got ...val is not an iterator
  this.newJSONCountryArr = Object.entries(this.countries)
    .map(([key, val]) => [...val, key]);
  console.log('Result: ', this.newJSONCountryArr);

  if (this.countries) {
    this.meta.countryOptions.push(this.services.countryList);
  } else {
    console.log('Whoops! ')
  }
}

标签: typescriptlodash

解决方案


请参阅上面 UPDATE 中的解决方案

// Now to make a new array for only country code and name
// ************* THIS IS THE SOLUTION **************
var results =_.map(this.countries, function(res) { 1
  console.log('result: ', { country_name: res.columns[1].paramValue, country_alpha2_code: res.columns[2].paramValue });
  return { country_name: res.columns[1].paramValue, country_alpha2_code: res.columns[2].paramValue }; 
});

推荐阅读