通过两个数组ES6

时间:2018-12-18 13:13:45

标签: javascript data-structures

数组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"}
    ]
  }
}

2 个答案:

答案 0 :(得分:0)

这是一个简单的解决方案...

// This is essntially the output.
const result = {};


// Your array or names.
const namedSet = ["BELT", "Berries"];


// Your data array.
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"}
];


// Iterate over both array's and handle the data.
sortedLine.map(i => namedSet.map(j => {
    if (!Array.isArray(result[j])) result[j] = [];
    if (i.name.indexOf(j) > -1) result[j].push(i);
}));


// Proof that it works.
console.log(result);


// Not sure what this does... But it's here anyway!
const reqArray = {lines: result};

答案 1 :(得分:0)

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