首页 > 解决方案 > 如何按不同的属性将对象列表分组到字符串中?

问题描述

我在 Javascript 中有数百个对象的数组,对象如下所示:

object1 = { objectClass : Car, parentClass : Vehicle, name : BMW }
object2 = { objectClass : Bicycle, parentClass : Vehicle, name : Giant }
object3 = { objectClass : Truck, parentClass : Vehicle, name : VW }
object4 = { objectClass : Country, parentClass : Europe, name : Germany }
object5 = { objectClass : Tradition, parentClass : Europe, name : Hats}

我想根据“parentClass”属性将所有对象分组为一个大字符串或字符串数​​组,并显示它们的“name”属性,根据上面的示例,字符串/字符串应该如下所示:

Vehicle : BMW, GIANT, VW
Europe : Germany, Hats 

在 Javascript 中对此有什么好的解决方案?首先十分感谢 !

标签: javascripttypescriptalgorithmsorting

解决方案


假设您有一个Array给定的对象(因为它是这里的最佳选择),您可以遍历元素并运行一个简单的if - else if块并通过将它们推入两个不同的数组来根据需要对值进行分类,它看起来像这个

const objs = [
    { objectClass : 'Car', parentClass : 'Vehicle', name : 'BMW' },
    { objectClass : 'Bicycle', parentClass : 'Vehicle', name : 'Giant' }
] // so on, add as many objects as you want to

// arrays for categorization
const Vehicle = [];
const Europe = [];

// iterating through the array
objs.forEach(obj => {
    if (obj.parentClass === 'Vehicle') Vehicle.push(obj.name);
    else if (obj.parentClass === 'Europe') Europe.push(obj.name);
});

// displaying results
console.log(Vehicle.length !== 0 ? `Vehicle: ${Vehicle.join(', ')}` : `Vehicle: none`);
console.log(Europe.length !== 0 ? `Europe: ${Europe.join(', ')}` : `Europe: none`);

推荐阅读