在es6中修改数组后,Javascript删除并插入项目

时间:2018-03-04 23:24:15

标签: javascript

我坚持如何修改我的阵列

我有一个数组样本

var data = [
  {id:1, time_in: [{in:12, out:13},{in:122, out:143}]},
  {id:2, time_in: []}  //this has time_in beign empty
]

所以我想修改我的数组,以便最后如果数组中的每个项目都有多个time_in创建为新行

所以最后我希望能够实现

var final_array = [
      [
       {id:1, in_time:12, out_time:13},
       {id:1, in_time:122, out_time:143},
       {id:2, in_time:null, out_time:null}
     ]

所以我试过了

data.forEach(item=>{
  const itemindex = data.indexOf(item) //get its index  
  if(item.time_in.length >0){
    data.splice(itemindex , 1) //first remove the item
     //stuck here on how to readd the item to the array and create new rows
       on the previous index


   }else{
     //just declare the intime and out null
    data.in_time = null;
    data.out_time=null;

   }
 }

我如何继续。

2 个答案:

答案 0 :(得分:7)

您可以使用reduce执行此操作。 这是一个例子:



var data = [
  {id:1, time_in: [{in:12, out:13},{in:122, out:143}]},
  {id:2, time_in: []}  //this has time_in beign empty
];

var data = data.reduce((a, c) => {
   if(c.time_in.length){
      c.time_in.forEach(v => {
         a.push({id: c.id, in_time: v.in, out_time: v.out});
      });
   }else{
      a.push({id: c.id, in_time: null, out_time: null});
   }
   return a;
}, []);

console.log(data);




答案 1 :(得分:0)

尽管接受的答案是好的,但我想尝试在没有.reduce的情况下进行练习。 formattedDataNested返回数组内部的数组,因此需要在formattedData中展平。



const data = [
  { id: 1, time_in: [{in: 12, out: 13}, {in: 122, out: 143}]},
  { id: 2, time_in: [] },
];

const formattedDataNested = data.map(row => {
  if (row.time_in.length == 0) {
    return {
      id: row.id,
      time_in: null,
      time_out: null,
    };
  }

  return row.time_in.map(value => ({
    id: row.id,
    time_in: value.in,
    time_out: value.out,
  }));
});

const formattedData = [].concat(...formattedDataNested);

console.log(formattedData);