如何在angular6中合并数组值相同的id对象?

时间:2019-05-21 14:13:09

标签: arrays json angular filter

在这里,我的棱角计划得到了回应

const testArray = [
{PackageID: 7, FormsList: [{Form_Name: "string One"}]}
{PackageID: 7, FormsList: [{Form_Name: "string Two"}]}
{PackageID: 7, FormsList: [{Form_Name: "string Three"}]}

{PackageID: 11, FormsList: [{Form_Name: "string One"}]}
{PackageID: 11, FormsList: [{Form_Name: "string One"}]}
{PackageID: 11, FormsList: [{Form_Name: "string One"}]}]

获取此数组后,我想与FormsList数组合并,如下所示相同的ID

const testArray = [
{PackageID: 7, FormsList: [{Form_Name: "string One"}, {Form_Name: "string Two"}, {Form_Name: "string Three"}]}  
{PackageID: 11, FormsList:  [{Form_Name: "string One"}, {Form_Name: "string Two"}, {Form_Name: "string Three"}]}]

和合并后如何删除特定的FormList> Form_Name选择的对象。

例如,我正在获取这样的删除值

const deleteArray = [{PackageID: 7, FormsList: [{Form_Name: "string Two"}]}]

测试数组结果没有第二个对象,如下面的代码

const testArray = [{PackageID: 7, FormsList: [{Form_Name: "string One"}, {Form_Name: "string Three"}]}, {PackageID: 11, FormsList:  [{Form_Name: "string One"}, {Form_Name: "string Two"}, {Form_Name: "string Three"}]}]

请对此提供帮助。

更新屏幕截图 enter image description here

2 个答案:

答案 0 :(得分:1)

合并,请注意:使用let代替const

let tempArr : {
  PackageId : number,
  FormsList : {
    Form_Name : string
  }[]
}[] = []

// Iterate over test array
for(let testItem of testArray){
    // Check if item id exist
    if(tempArr.find(i=>i.PackageId==testItem.PackageID)){
        // Itearte over form list
        for(let testItemForm of testItem.FormsList){
      tempArr.find(i=>i.PackageId==testItem.PackageID).FormsList.push(testItemForm)
        }
    }else{
        tempArr.push({
            PackageId : testItem.PackageID,
            FormsList : testItem.FormsList
        })
    }
}

// Copy back
testArray = tempArr

删除

// Iterate over test array
for(let testItem of testArray){
    // Itearte over delete array
    for(let deleteItem of deleteArray){
        // Check if id matches  
        if(testItem.PackageID == deleteItem.PackageID){
            // Itearte over delete form list
            for(let deleteItemForm of deleteItem.FormsList){
                // Filter form list of test item
                testItem.FormsList = testItem.FormsList.filter(f=>f.Form_Name!=deleteItemForm.Form_Name)
            }
        }
     }
}

答案 1 :(得分:1)

所以,让我们开始吧! 我们应该做的第一件事是创建PackageID's

的列表
const ids = testArray.map(item => item.PackageID)

,然后让我们从该数组获取唯一值。为此,我们需要进行两步操作

  1. 创建函数distinct
const distinct = (value, index, self) => {
    return self.indexOf(value) === index
}
  1. 创建uniq ID的列表
const uniqIds = ids.filter(distinct)

现在我们可以合并testArray

const res = uniqIds.map(id => {
    let tmp = []
    const arr = testArray.filter(item => item.PackageID === id)

    arr.forEach(item => {
        tmp.push(...item.FormsList)
    })

    return { PackageID: id, FormsList: tmp }
})

我希望它将对您有帮助