5 javascript typescript lodash angular
我有一个看起来像这样的对象数组。我使用 .groupBy 和 lodash 使它看起来像那样。
状态.ts
STATES: Object[] = [
{
USA: [
{
name: 'Alabama',
abbreviation: 'AL',
country: 'USA'
},
{
name: 'Alaska',
abbreviation: 'AK',
country: 'USA'
}
]
},
{
Canada: [
{
name: 'Alberta',
abbreviation: 'ALB',
country: 'Canada'
}
]
}
];
Run Code Online (Sandbox Code Playgroud)
我需要它看起来像这样:
stateList:StateDropdownItem[] =[
{
label: 'USA',
items: [
{label: 'AL', value: 'Alabama'},
{label: 'AK', value: 'Alaska'},
]
},
.
.
]
Run Code Online (Sandbox Code Playgroud)
我已经尝试了下面的代码,但它不起作用。当我将它打印到控制台时,undefiened即使我尝试在没有 forloop 的情况下放置元素,也会出现以下错误Cannot read property 'push' of undefined
TS
dropdownOfStates: StateDropdownItem[];
.
.
dropdownBuilder() {
const STATES_BY_COUNTRY = this.getStatesByCountry();
let tempItem;
for (let i = 0; i < STATES_BY_COUNTRY.length; i++) {
tempItem = STATES_BY_COUNTRY[i];
this.dropdownOfStates.push(
new StateDropdownItem('KEY COUNTRY VALUE HERE', [
tempItem.abbreviation,
tempItem.name
])
);
}
}
Run Code Online (Sandbox Code Playgroud)
按国家/地区打印使用 .groupBy 和 lodash groupby 对象的结果后的 Console.log
您可以使用map数组的功能来转换它们的结构。
下面的代码应该将它转换成你想要的结构。您可以单击“运行代码片段”以查看输出
let states = [
{
USA: [
{
name: 'Alabama',
abbreviation: 'AL',
country: 'USA'
},
{
name: 'Alaska',
abbreviation: 'AK',
country: 'USA'
}
]
},
{
Canada: [
{
name: 'Alberta',
abbreviation: 'ALB',
country: 'Canada'
}
]
}
];
// Use the code below to transform
let res = states.map((val) => {
let country = Object.keys(val)[0]; // Get the name of the country, e.g. USA
return { // Return the new object structure
label: country,
items: val[country].map((item) => ({label: item.abbreviation, value: item.name}))
}
});
// Log the value
console.log(res);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12313 次 |
| 最近记录: |