将多个数组抽取重复元素作为key值,其他作为键值的对象组

原数组如下:

options:[
                    {
                    value: 'Asia',
                    label: 'Asia',
                    children: [
                        { value: 'Beijing', label: 'Beijing' },
                        { value: 'Shanghai', label: 'Shanghai' },
                        { value: 'Hangzhou', label: 'Hangzhou' },
                        { value: 'Tokyo', label: 'Tokyo' },
                        { value: 'Osaka', label: 'Osaka' },
                        { value: 'Kyoto', label: 'Kyoto' },
                        
                    ],
                    },
                    {
                    value: 'Europe',
                    label: 'Europe',
                    children: [
                        { value: 'London', label: 'London' },
                        { value: 'Birmingham', label: 'Birmingham' },
                        { value: 'Manchester', label: 'Manchester' },
                        { value: 'Paris', label: 'Paris' },
                        { value: 'Marseille', label: 'Marseille' },
                        { value: 'Lyon', label: 'Lyon' },
                    ],
                    },
                    {
                    value: 'North America',
                    label: 'North America',
                    children: [
                        { value: 'New York', label: 'New York' },
                        { value: 'Los Angeles', label: 'Los Angeles' },
                        { value: 'Washington', label: 'Washington' },
                        { value: 'Toronto', label: 'Toronto' },
                        { value: 'Montreal', label: 'Montreal' },
                        { value: 'Ottawa', label: 'Ottawa' },
                        
                    ],
                    },
                ]

数组选中,如下:

list:[
  ['Asia', 'Beijing'],
  ['Asia', 'Hangzhou'],
  ['Europe', 'London'],
  ['Europe', 'Birmingham'],
  ['Europe', 'Manchester'],
  ['Europe', 'Paris' ],
  ['Europe', 'Marseille'],
  ['Europe', 'Lyon'],
  ['North America', 'Washington']
]

想将数组转化成

[{'Asia':'Beijing,Hangzhou'},{'Europe':'London,Birmingham,Manchester,Paris,Marseille,Lyon'},{'North America':'Washington'}],

就是相当于抽取Asia ,Europe,North America下的内容组合在一起;

el-cascader里面的多选开启是的绑定输出值list

阅读 1k
1 个回答
const getFormatList = (list)=>{
  const temp =  list.reduce((prev,[parent,child])=>{
    prev[parent] ||=[]
    prev[parent].push(child)
    return prev
  },{})
  return Object.keys(temp).map(key=> ({[key]:temp[key]}))
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏