首页 > 解决方案 > 将数组中的对象拼接到新数组中

问题描述

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",
  },
]

标签: javascript

解决方案


首先,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)


推荐阅读