我有两个对象数组,我想将它们组合成一个新数组,根据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",
},
]
答案 0 :(得分:3)
您可以使用flatMap
来实现。这是一个实现。
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 result = arrayTwo.flatMap((p,i)=>{
position = arrayOne.find(k=>k.previewNumber===i);
return position ? [position, p] : p
});
console.log(result);
或者您可以将arrayOne转换为对象。像这样:
const arrayOne = [ { "title": "A Project", "slug": "a-project", "previewNumber": 2, }, { "title": "New Project", "slug": "new-project", "previewNumber": 4, }];
const mapped = Object.fromEntries(arrayOne.map(p=>[p.previewNumber,p]));
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 result = arrayTwo.flatMap((p,i)=>mapped[i] ? [mapped[i], p] : p);
console.log(result);
答案 1 :(得分:2)
首先,制作newArray
的{{1}}副本。之后,您可以通过arrayTwo
arrayOne
添加到newArray
中
previewNumber + index
完整演示
const newArray = [...arrayTwo]
arrayOne.forEach((el, index) => {
newArray.splice(el.previewNumber + index, 0, el)
})
console.log(newArray)