在数组内的对象内填充数组

时间:2020-01-31 06:26:28

标签: javascript arrays multidimensional-array

我有一个类似于以下的数组-该代码对于第一个对象(Id = 1)完美工作,但是对于第二个和第三个对象(id = 2&id = 3),[categoryID = 3]而不是前2个然后是3。

我尝试了各种排列,但没有任何乐趣。

let documentItems = [{
    id: 1, //I want to copy this id as CategoryID to Items below
    title: "All Staff",
    Items: [{
        id: 3,
        // This is where I want to create the CategoryID
        PolicyName: "A Policy",
        AppliesTo: [1]
      },
      {
        id: 4,
        PolicyName: "A Completely Different Policy",
        AppliesTo: [1]
      }
    ]
  },
  {
    id: 2,
    title: "Management",
    Items: [{
      id: 2,
      PolicyName: "Another different Policy",
      AppliesTo: [2, 3]
    }]
  },
  {
    id: 3,
    title: "Admin",
    Items: [{
      id: 1,
      PolicyName: "A third Policy",
      AppliesTo: [2, 3]
    }]
  }
]

documentItems.forEach((el) => {
  let id = el.id
  el.Items.forEach((el2) => {
    el2.categoryID = id
  })
});

console.log(documentItems)
我试图说明的结果(上述)

let documentItems = [{
    id: 1, //I want to copy this id as CategoryID to Items below
    title: "All Staff",
    Items: [{
        id: 3,
        CategoryID: 1,
        PolicyName: "A Policy",
        AppliesTo: [1]
      },
      {
        id: 4,
        CategoryID: 1,
        PolicyName: "A Completely Different Policy",
        AppliesTo: [1]
      }
    ]
  },
  {
    id: 2,
    title: "Management",
    Items: [{
      id: 2,
      CategoryID: 3,// SHOULD BE 2 INCORRECT
      PolicyName: "Another different Policy",
      AppliesTo: [2, 3]
    }]
  },
  {
    id: 3,
    title: "Admin",
    Items: [{
      id: 1,
      CategoryID: 3, // Should be 3 - CORRECT
      PolicyName: "A third Policy",
      AppliesTo: [2, 3]
    }]
  }
]

0 个答案:

没有答案