javascript - 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?
解决方案
您可以做的是制作原始数组的深层副本。然后在该数组中的适当位置插入新元素,然后重置所有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);
推荐阅读
- architecture - 重用基础软件工程和组件基础软件工程之间的区别?
- visual-studio-2017 - 使用 SQL Server 2017 和 Visual Studio 2017 的常用 python 库
- microsoft-teams - 禁用用户后,他/她在 Microsoft Teams 中的消息会被删除吗?
- c++ - 这些问题都暗示着同样的事情吗?
- javascript - 在 Nodejs 和 Express 中使用 JQuery 需要帮助
- css - 我的 html.erb 视图页面内的内联 css 样式的背景图像仅在开发中显示,但在 heroku 上不显示生产阶段
- react-native - 标题空白和 ImageBackground
- apache-kafka-streams - kafka 流中的聚合和状态存储保留
- php - 使用 php 和 htaccess 创建人造 dyndns
- c# - Unity - 如何制作有弹性的绳索?