我对 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"}];
map 不是个好主意吗?条件我用 momento 检查并检查语句是否正确我只是想如何将对象推到第二个和第四个之间并像代码中那样制作 asc_id?
最佳答案
您可以做的是对原始数组进行深度复制。然后将新元素插入该数组中的适当位置,然后重置所有 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);
关于javascript在特定点id处将对象插入数组并增加其他id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51108985/