javascript - 如何按不同的属性将对象列表分组到字符串中?
问题描述
我在 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 中对此有什么好的解决方案?首先十分感谢 !
解决方案
假设您有一个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`);
推荐阅读
- android - 完成 SFTP 传输后出现 NullPointerException
- php - PHP Mailer 没有显示错误但不发送电子邮件
- linux - 如何将 iptables-service 规则转换为 firewalld 规则?
- c# - .Net DataGridView Rows.Add 和 Rows.AddRange 与自定义 DataGridViewRow 的区别
- python - 使用 O-Auth 在 Flask 应用程序上访问 Google My Business API 的问题
- scala - 如何确定 if 语句中哪个条件为假
- react-final-form - 反应最终表单 FieldArray、侦听器和在表单外显示来自 api 调用的数据的问题
- java - 使用 PCF 用户提供的服务创建数据源失败
- python - 使用 cmake 和 pybind11 构建示例应用程序时找不到 Python.h
- python - gunicorn ModuleNotFound 错误,以前工作过