首页 > 解决方案 > 如果对象 B 中存在属性,则替换对象 A 中的匹配值

问题描述

我有一个包含一些对象的数组。特别是有两个从 API 返回的对象。我有来源和突出显示键。源总是返回,如果有要突出显示的字段,那么突出显示也会回来。

我想匹配突出显示的任何属性并使用它并替换源中的属性。例如

document = {
    summary: {
        took: 1,
        count: 230
    },
    results: [
           {
            source: {
                surname: 'Jones',
                forename: 'Tom'
            },
            highlight: {
                surname: ['<em>Jones</em>'],
            }
        }
    ]
}

预期结果:

document = {
    summary: {
        took: 1,
        count: 230
    },
    results: [
         {
            source: {
                surname: ['<em>Jones</em>'],
                forename: 'Tom'
            },
            highlight: {
                surname: ['<em>Jones</em>'],
            }
        }
    ]
}

我见过一些比较两个数组而不是同一个数组中的两个对象的解决方案。有任何想法吗?

标签: javascriptarrayssortingobject

解决方案


如果您不介意document就地更新对象,则可以循环results并复制以下条目highlight

for (const {source, highlight} of document.results) {
    for (const key of Object.keys(highlight)) {
        if (key in source) {
            source[key] = highlight[key];
        }
    }
}

现场示例:

// I used `doc` because `document` conflicts with the built-in global
// (I could have used a scoping block)
const doc = {
    summary: {
        took: 1,
        count: 230
    },
    results: [
           {
            source: {
                surname: 'Jones',
                forename: 'Tom'
            },
            highlight: {
                surname: ['<em>Jones</em>'],
            }
        }
    ]
};
for (const {source, highlight} of doc.results) {
    for (const key of Object.keys(highlight)) {
        if (key in source) {
            source[key] = highlight[key];
        }
    }
}
console.log(JSON.stringify(doc, null, 4));
.as-console-wrapper {
    max-height: 100% !important;
}

我猜这些对象不会有任何继承属性,所以你可以使用for (const key in highlight)for (const key of Object.keys(highlight))不是创建临时数组:

for (const {source, highlight} of document.results) {
    for (const key in highlight) {
        if (key in source) {
            source[key] = highlight[key];
        }
    }
}

现场示例:

// I used `doc` because `document` conflicts with the built-in global
// (I could have used a scoping block)
const doc = {
    summary: {
        took: 1,
        count: 230
    },
    results: [
           {
            source: {
                surname: 'Jones',
                forename: 'Tom'
            },
            highlight: {
                surname: ['<em>Jones</em>'],
            }
        }
    ]
};
for (const {source, highlight} of doc.results) {
    for (const key in highlight) {
        if (key in source) {
            source[key] = highlight[key];
        }
    }
}
console.log(JSON.stringify(doc, null, 4));
.as-console-wrapper {
    max-height: 100% !important;
}

除非我确定它会产生重要的性能差异,否则我更喜欢使用它,Object.keys所以我只能获得自己的属性,而不是继承的属性,但我怀疑它在这里会有所作为。


推荐阅读