首页 > 解决方案 > javascript 在特定点 id 处将对象插入数组并增加其他 id

问题描述

我对 js 数组没什么问题。我想在 if 语句上插入对象并在其他对象上增加 id

    var arr=[{asc_id:1, date:2018-06-29, name:"first"},
         {asc_id:2, date:2018-06-30, name:"second"}, 
         {asc_id:3, date:2018-07-10, name:"fourth"},
         {asc_id:4, date:2018-07-10, name:"fifth"}];
var checkedItem={asc_id:4, date:2018-06-30, name:"third"};

let savingDate = moment(checkedItem.date)
var newArr = arr.map((item,key)=>{
  if(savingDate.isSame(item.date) || savingDate.isAfter(item.date)){
    console.log(true)
    return{
      //code here
    }
  }else{
    return{
      //code here
    }
    console.log(false)
  }
})
console.log(newArr)

我想让新数组看起来像

newArr=[{asc_id:1, date:2018-06-29, name:"first"},
     {asc_id:2, date:2018-06-30, name:"second"}, 
     {asc_id:3, date:2018-06-30, name:"third"},
     {asc_id:4, date:2018-07-10, name:"fourth"},
     {asc_id:5, date:2018-07-10, name:"fifth"}];

地图不是个好主意吗?条件我用momento检查并且检查语句是正确的,只有我想如何在第二个和第四个之间推送对象并在代码中制作asc_id?

标签: javascriptarrays

解决方案


您可以做的是制作原始数组的深层副本。然后在该数组中的适当位置插入新元素,然后重置所有asc_id属性。

 var arr=[{asc_id:1, date:"2018-06-29", name:"first"},
         {asc_id:2, date:"2018-06-30", name:"second"}, 
         {asc_id:3, date:"2018-07-10", name:"fourth"},
         {asc_id:4, date:"2018-07-10", name:"fifth"}];
var checkedItem={asc_id:4, date:"2018-06-30", name:"third"};

var newArr = arr.map(e => Object.assign({}, e));
var insertPos = newArr.findIndex(({date}) => date > checkedItem.date);
if (insertPos == -1) { // If not found, insert at end
    insertPos = newArr.length;
}
newArr.splice(insertPos, 0, checkedItem);
newArr.forEach((e, i) => e.asc_id = i + 1);
console.log(newArr);


推荐阅读