首页 > 解决方案 > 从两个数组 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"}
    ]
  }
}

标签: javascriptdata-structures

解决方案


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; }, {} ) } );

推荐阅读