typescript - 我需要遍历一个复杂的 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! ')
}
}
解决方案
请参阅上面 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 };
});
推荐阅读
- prolog - 序言中的局部否定
- java - 如何在不改变 Java 中的顺序的情况下找到一组整数的顺序?
- html - 是否可以将规则应用于标签嵌套中的特定标签?
- redux - 在 redux 中观察 redux-saga 动作
- google-bigquery - 使用源谷歌驱动器创建表模式并在 bigquery 表中加载数据
- service - 无法设置服务的优先级
- swift - 如何使用 SwiftUI 的 onDelete() 函数访问数组位置
- python - 用 OpenCV + Python 拼接四个图像
- swift - ScrollView 在关闭 ViewController 并调用 viewDidLoad 时不会重新加载
- python - 从网站抓取价格为零的问题