首页 > 解决方案 > 无法从对象数组中删除重复项

问题描述

我正在尝试按 ID 删除重复项,而我的数组似乎无法编辑。我确定这是范围或语法问题,但我无法发现它。

    let testarray = []
    moduleobjects.forEach((firstmoduleobject,bigindex)=>{
        let matchedmodules = [firstmoduleobject]
        firstmoduleobject.coords.forEach(firstline=>{
            let x1 = firstline[0].x
            let x2 = firstline[1].x
            let y1 = firstline[0].y
            let y2 = firstline[1].y

            moduleobjects.forEach((object,index)=>{
                if(matchedmodules.includes(object)){return}else{
                    if(!object===firstmoduleobject){
                        object.coords.forEach(line=>{
                            line.forEach(point=>{
                                if (point.x===x1||x2){
                                    if(!_.includes(matchedmodules,object)){
                                        
                                        matchedmodules.push(object)

                                    }
                                }
                            })
                        })
                    }
                }
                console.log()
                

            })
            function removeDuplicates(originalArray, prop) {
                var newArray = [];
                var lookupObject  = {};
           
                for(var i in originalArray) {
                   lookupObject[originalArray[i][prop]] = originalArray[i];
                }
           
                for(i in lookupObject) {
                    newArray.push(lookupObject[i]);
                }
                 return newArray;
            }
              testarray.push(removeDuplicates(matchedmodules,'id'))
            console.log(testarray.length)
        })
    })
    finalarray=[]
    testarray.forEach(array=>{
        let test = _.uniqBy(array,'id')
        finalarray.push(test)
    })

    fs.writeFileSync('testresults.json',JSON.stringify(finalarray))

有 3 点我尝试处理重复项。当对象被推入'matchedmodules'数组时,当匹配的模块数组被推入'testarray'数组时,最后'testarray'数组通过_.uniqBy过滤。

模块对象的结构如下:

let moduleobject = {
            id:index,
            coords:[],
            center:{}
        }

它在matchedmodules数组中的样子

  [
{
  "id": 18,
  "coords": [
    [
      { "x": 1604, "y": 498 },
      { "x": 1599, "y": 552 }
    ],
    [
      { "x": 1599, "y": 552 },
      { "x": 1631, "y": 555 }
    ],
    [
      { "x": 1631, "y": 555 },
      { "x": 1636, "y": 501 }
    ],
    [
      { "x": 1636, "y": 501 },
      { "x": 1604, "y": 498 }
    ]
  ],
  "center": { "x": 1617.5, "y": 526.5 }
}

]

这样做的主要目标是将模块与共享相同 x 或 y 值的其他模块配对。目前这仅适用于 x,但我计划在找出这些重复项后复制/粘贴和扩展 y。

值得注意的是,所有的欺骗都在 4 中。每个对象有 4 个,我猜是因为匹配总共发生了 4 次。

感谢和欢迎任何和所有帮助!

感谢您的时间和专业知识!

标签: node.jslodash

解决方案


推荐阅读