【问题标题】:How to compare list of array to another array using typescript如何使用打字稿将数组列表与另一个数组进行比较
【发布时间】:2022-01-26 11:24:03
【问题描述】:

我有一个数组列表和一个数组。如果 productID 和 attributesData 匹配返回我下面给出的列表结构,我想像这样比较这两个数组

列表1:

    {
        "unitPrice": "800.0",
        "productTypeTitle": "TYPE",
       
        "productId": "470",
        
        "attributesData": [
            {
                "attributeName": "COLOR",
                "attributeData": "BLUE"
            },
            {
                "attributeName": "SIZE",
                "attributeData": "36"
            },
           {..}
        ],
        "count": 2,
        "shopid": "53",
        "sessionid": "1643195257593",
...
    },
    {
        },...
]

列表2:

{
    "unitPrice": "800.0",
    "productTypeTitle": "TYPE",
    "productId": "470",
    "attributesData": [
        {
            "attributeName": "SIZE",
            "attributeData": "42"
        },
        {
            "attributeName": "COLOR",
            "attributeData": "Orange"
        },{...}
    ]
...
}

这里productId是一样的但是attributesData不一样我怎么知道。我可以检查productId是否相同但无法比较attributesData。我怎样才能有效地解决这个问题

【问题讨论】:

    标签: arrays typescript arraylist compare


    【解决方案1】:

    你可以使用 lodash isEqual,https://docs-lodash.com/v4/is-equal/

    function isEqual(list1,list2):boolean{
    return isEqual(list1,list2)
    }
    

    如果不使用 lodash - 然后你需要循环遍历所有属性并进行比较

    function deepEqual(a, b) {
        if (a === b) {
            return true;
        }
     
        if (a == null || typeof(a) != "object" ||
            b == null || typeof(b) != "object")
        {
            return false;
        }
     
        var propertiesInA = 0, propertiesInB = 0;
        for (var property in a) {
            propertiesInA += 1;
        }
        for (var property in b) {
            propertiesInB += 1;
            if (!(property in a) || !deepEqual(a[property], b[property])) {
                return false;        
            }
        }        
        return propertiesInA == propertiesInB;
    }
    

    此链接来源 enter link description here

    因为在进程相等时对象是引用

    【讨论】:

    • 这对我不起作用你的函数比较整个列表我需要根据 productID 和 attributesData 进行比较
    猜你喜欢
    • 1970-01-01
    • 2021-05-18
    • 1970-01-01
    • 2014-07-27
    • 1970-01-01
    • 1970-01-01
    • 2018-08-04
    • 2010-09-21
    • 2017-07-03
    相关资源
    最近更新 更多