繁体   English   中英

如何使用 typescript 将数组列表与另一个数组进行比较

[英]How to compare list of array to another array using typescript

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

清单 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。我怎样才能有效地解决这个问题

你可以使用 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;
}

此链接来源在此处输入链接描述

因为 object 是进程相等时的参考

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM