【问题标题】:cluster Objects of Arrays (JavaScript)数组的集群对象 (JavaScript)
【发布时间】:2021-09-18 22:06:53
【问题描述】:

如何通过将数组与isNew / isModified / isDeleted 进行比较来对数组的对象进行通用聚类?

originalArray = [
    {id: 1, name: "foo", next: true},
    {id: 2, name: "bar", next: false}];

modifiedArray = [
    {id: 2, name: "bar", next: true},
    {id: 3, name: "baz", next: false} ];

result = function(originalArray, modifiedArray);

//OUTPUT:
result = 
    {
        isNew: [ {id: 3, name: "baz", next: false} ], 
        isModified: [ {id: 2, name: "bar", next: true} ],
        isDeleted: [ {id: 1, name: "foo", next: true} ]
    }

【问题讨论】:

  • 请提及您到目前为止所做的尝试。

标签: javascript typescript


【解决方案1】:

您可以使用这样的函数来获得所需的结果。

function check(originalArray, modifiedArray) {
    const isNew = [];
    const isDeleted = [];
    const isModified = [];
    // any element of modified array that is not in originalArray is a newly added element
    modifiedArray.forEach((ma) => {
        const originalElem = originalArray.find((oa) => oa.id === ma.id);
        if (originalElem == null) {
            isNew.push(ma);
        } else if (checkModified(originalElem, ma)) {
            // if element exists in both the arrays, it may have been modified
            isModified.push(ma);
        }
    });

    // any element of original array that is not in modifiedArray is a deleted element
    originalArray.forEach((oa) => {
        const modifiedElem = modifiedArray.find((ma) => ma.id === oa.id);
        if (modifiedElem == null) {
            isDeleted.push(oa);
        }
    });

    function checkModified(originalElem, modifiedElem) {
        if (originalElem.next !== modifiedElem.next) {
            return true;
        }
    }

    return {
        isNew,
        isDeleted,
        isModified
    }
}

const originalList = [
    {id: 0, name: "xyz", next: true},
    {id: 1, name: "foo", next: true},
    {id: 2, name: "bar", next: false}];

const modifiedList = [
    {id: 2, name: "bar", next: true},
    {id: 3, name: "baz", next: false} ];

const result = check(originalList, modifiedList);
console.log(result);

【讨论】:

    猜你喜欢
    • 2013-05-27
    • 2020-08-26
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 2022-06-16
    • 2020-11-24
    • 1970-01-01
    • 2022-01-12
    相关资源
    最近更新 更多