javascript - 将数组中的对象拼接到新数组中
问题描述
previewNumber
我有两个对象数组,我想将它们组合成一个新数组,根据作为索引的值将一个数组中的每个对象拼接到另一个数组中.splice
。我用过.map
,但它只循环长度arrayOne
,下面是一些示例代码,任何帮助将不胜感激
const arrayOne = [
{
"title": "A Project",
"slug": "a-project",
"previewNumber": 2,
},
{
"title": "New Project",
"slug": "new-project",
"previewNumber": 4,
}
]
const arrayTwo = [
{
"title": "Project 5546",
"slug": "project-5546",
},
{
"title": "Project 456",
"slug": "project-456",
},
{
"title": "Rand Project 467",
"slug": "rand-project-467",
},
{
"title": "Random Project 245",
"slug": "random-project-245",
},
{
"title": "Example Project",
"slug": "example-project",
},
]
const newArray = arrayOne.map((item) =>
arrayTwo.splice(item.previewNumber, 0, item)
);
console.log(newArray)
const desiredOutput = [
{
"title": "Project 5546",
"slug": "project-5546",
},
{
"title": "Project 456",
"slug": "project-456",
},
{
"title": "A Project",
"slug": "a-project",
"previewNumber": 2,
},
{
"title": "Rand Project 467",
"slug": "rand-project-467",
},
{
"title": "Random Project 245",
"slug": "random-project-245",
},
{
"title": "New Project",
"slug": "new-project",
"previewNumber": 4,
},
{
"title": "Example Project",
"slug": "example-project",
},
]
解决方案
首先,newArray
制作arrayTwo
. 之后,您可以arrayOne
通过newArray
拼接从previewNumber + index
const newArray = [...arrayTwo]
arrayOne.forEach((el, index) => {
newArray.splice(el.previewNumber + index, 0, el)
})
console.log(newArray)
完整演示
const arrayOne = [
{
title: "A Project",
slug: "a-project",
previewNumber: 2,
},
{
title: "New Project",
slug: "new-project",
previewNumber: 4,
},
]
const arrayTwo = [
{
title: "Project 5546",
slug: "project-5546",
},
{
title: "Project 456",
slug: "project-456",
},
{
title: "Rand Project 467",
slug: "rand-project-467",
},
{
title: "Random Project 245",
slug: "random-project-245",
},
{
title: "Example Project",
slug: "example-project",
},
]
const newArray = [...arrayTwo]
arrayOne.forEach((el, index) => {
newArray.splice(el.previewNumber + index, 0, el)
})
console.log(newArray)
推荐阅读
- algorithm - 如何获得一系列作品的最短时间?
- javascript - 如何让 console.clear() 在清除后不给出消息
- ruby-on-rails - 使用简单表单时如何删除必填字段中的星号?
- javascript - 如何在 1 个函数中多次调用语音识别?
- angular - 如何在 Angular6 上使用 colorFilter 和 ngx-leaflet
- java - RecyclerView 不显示来自 JSON 的数据
- javascript - 用javascript触发前进按钮
- typo3 - 全新安装最新的 TYPO3 9.5 LTS 后无法登录后端
- java - 为什么我的程序在获取字符串而不是字符时会自行终止?
- python - 如何在python中比较两个字典