我的模块就像这样:
[types.GET_PRODUCT_CATEGORIES] (state,{ stores }) {
state.product_categories = {}
console.log(stores);
stores.forEach(message => {
set(state.product_categories, message.id, message)
})
console.log('test')
console.log(state.product_categories)
},
console.log(stores)
的结果如下:
我想通过键parent_category_id
将对象更改为二维对象数组我该怎么做?
更新:
例如:
parent_category_id = 1,2,3
parent_category_name = asia,europa,africa
id = 4,5,6,7,8,9,20
name = japan,korea,arab,england,spain,italy,south africa
我想这样显示:
asia
japan
korea
arab
europa
england
spain
italy
africa
south africa
所以我需要将对象一维转换为对象二维
答案 0 :(得分:0)
我希望它能帮助您实现解决方案
var dataArr=[{
id:1,
name:'japan',
parent_category_id:1,
parent_category_name:'asia'
},{
id:2,
name:'england',
parent_category_id:2,
parent_category_name:'europa'
},{
id:3,
name:'korea',
parent_category_id:1,
parent_category_name:'asia'
},{
id:4,
name:'arab',
parent_category_id:1,
parent_category_name:'asia'
},{
id:5,
name:'south africa',
parent_category_id:3,
parent_category_name:'africa'
},{
id:6,
name:'spain',
parent_category_id:2,
parent_category_name:'europa'
},{
id:7,
name:'italy',
parent_category_id:2,
parent_category_name:'europa'
}],
output ={};
dataArr.map((item,index,arr)=>{
if(!output[item.parent_category_name]){
let result = arr.filter(val=>{
return val.parent_category_id==item.parent_category_id;
})
output[item.parent_category_name] = result.map(val=>{
return val.name;
});
}
});
console.log(output);

答案 1 :(得分:0)
这是我用于分组的功能:
const groupBy = (arr, keyFn) => {
const grouped = arr.reduce( (grouping, item) => {
const key = keyFn(item);
grouping[key] = grouping[key] || [];
grouping[key].push(item);
return grouping;
}, {} );
return Object.keys(grouped)
.map(key => { return {key: key, group: grouped[key]}; });
}
您可以这样称呼它:
const itemByCategoryName = (items) => {
const keyFn = item => item.parent_category_name
return groupBy(items, keyFn)
.map(group => { return { parent_category_name: group.key, grouped_items: group.group }; });
}
输出是一个带有键和嵌套数组项的对象数组。