将对象数组转换为其他对象数组-Javascript / Angular

时间:2018-08-25 06:45:00

标签: javascript angular typescript lodash

我有一个看起来像这样的对象数组。我使用带有lodash的.groupBy使其看起来像这样。

States.ts

STATES: Object[] = [
  {
    USA: [
      {
        name: 'Alabama',
        abbreviation: 'AL',
        country: 'USA'
      },
      {
        name: 'Alaska',
        abbreviation: 'AK',
        country: 'USA'
      }
    ]
  },
  {
    Canada: [
      {
        name: 'Alberta',
        abbreviation: 'ALB',
        country: 'Canada'
      }
    ]
  }
];

我需要它看起来像这样:

    stateList:StateDropdownItem[] =[ 
    {
       label: 'USA', 
       items: [
               {label: 'AL', value: 'Alabama'},
               {label: 'AK', value: 'Alaska'},
       ]
    },
    .
    .
   ]

我已经尝试了下面的代码,但是没有用。当我将其打印到控制台时,即使我尝试放置不带forloop的元素,也会显示undefiened

TS

Cannot read property 'push' of undefined

Console.log打印带有lodash的.groupBy结果后 groupby objects by country

2 个答案:

答案 0 :(得分:3)

您可以使用数组的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);

答案 1 :(得分:2)

以下是使用ES6和reduceObject.keysmap进行此操作的更为简洁的方法:

var data = [ { USA: [ { name: 'Alabama', abbreviation: 'AL', country: 'USA' }, { name: 'Alaska', abbreviation: 'AK', country: 'USA' } ] }, { Canada: [ { name: 'Alberta', abbreviation: 'ALB', country: 'Canada' } ] } ];

const result = data.reduce((r,c) => Object.keys(c).map(x => r.push({ label: x, items: c[x].map(y => ({label: y.abbreviation, value: y.name }))})) && r, [])

console.log(result)

这是扩展的变体:

var data = [ { USA: [ { name: 'Alabama', abbreviation: 'AL', country: 'USA' }, { name: 'Alaska', abbreviation: 'AK', country: 'USA' } ] }, { Canada: [ { name: 'Alberta', abbreviation: 'ALB', country: 'Canada' } ] } ];

const result = data.reduce((r,c) => {
   Object.keys(c).map(x => {
     r.push({ label: x, items: c[x].map(y => ({label: y.abbreviation, value: y.name }))})})
	return r}, [])

console.log(result)