javascript - 从两个数组 ES6 创建一个对象
问题描述
阵列 1:
sortedLine= [
{siteRef: "CH1", productionLineId: 5, name: "BELT 0"},
{siteRef: "CH1", productionLineId: 6, name: "BELT 2"},
{siteRef: "CH1", productionLineId: 7, name: "BELT 3"},
{siteRef: "CH1", productionLineId: 8, name: "BELT 4"},
{siteRef: "CH1", productionLineId: 9, name: "Berries 1"},
{siteRef: "CH1", productionLineId: 10, name: "Berries 2"},
{siteRef: "CH1", productionLineId: 12, name: "Berries 3"}
]
阵列 2:
namedSet = ["BELT", "Berries"]
所需对象:
reqArray = {
lines: {
"BELT":[
{siteRef: "CH1", productionLineId: 5, name: "BELT 0"},
{siteRef: "CH1", productionLineId: 6, name: "BELT 2"},
{siteRef: "CH1", productionLineId: 7, name: "BELT 3"},
{siteRef: "CH1", productionLineId: 8, name: "BELT 4"}
],
"Berries":[
{siteRef: "CH1", productionLineId: 9, name: "Berries 1"},
{siteRef: "CH1", productionLineId: 10, name: "Berries 2"},
{siteRef: "CH1", productionLineId: 12, name: "Berries 3"}
]
}
}
解决方案
const sortedLine= [
{siteRef: "CH1", productionLineId: 5, name: "BELT 0"},
{siteRef: "CH1", productionLineId: 6, name: "BELT 2"},
{siteRef: "CH1", productionLineId: 7, name: "BELT 3"},
{siteRef: "CH1", productionLineId: 8, name: "BELT 4"},
{siteRef: "CH1", productionLineId: 9, name: "Berries 1"},
{siteRef: "CH1", productionLineId: 10, name: "Berries 2"},
{siteRef: "CH1", productionLineId: 12, name: "Berries 3"}
];
const namedSet = ["BELT", "Berries"];
const reqArray = sortedLine.reduce( ( a, v ) => {
namedSet.forEach( s => {
if ( v.name.startsWith( s ) ) a.lines[ s ].push( v );
});
return a;
}, { lines: namedSet.reduce( ( a, v ) => { a[ v ] = []; return a; }, {} ) } );
推荐阅读
- dc.js - dc.js 带条形和折线的复合图表。在栏上实现单选
- python - 使用实体嵌入和 Keras 功能 API 将文本与分类特征相结合
- java - Java - sc.nextDouble() - 换行
- php - Vimeo API 获取结果为空的请求
- c# - 保存前设置值
- string-formatting - 字符串末尾的百分比-S (%s) 有什么用?(不是字符串格式)
- swift - 在 Swift 4.0 中 - 从代码添加时不会出现圆形
- javascript - 从数据库中获取月份并使用 javascript / ajax 发送到另一个页面?
- php - 计算多个表的行并单独返回结果?
- hibernate - java.lang.NoSuchMethodError: org.hibernate.StatelessSession.createQuery(Ljava/lang/String;)Lorg/hibernate/query/Query;