javascript - 如果对象 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>'],
}
}
]
}
我见过一些比较两个数组而不是同一个数组中的两个对象的解决方案。有任何想法吗?
解决方案
如果您不介意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
所以我只能获得自己的属性,而不是继承的属性,但我怀疑它在这里会有所作为。
推荐阅读
- amazon-web-services - 从在 ec2 服务器上运行的脚本记录打印语句?
- android - Jenkins Android groovy.lang.MissingPropertyException:没有这样的属性:HOME 类:groovy.lang.Binding
- jquery - 如何在 Moodle(小胡子)中使用 Javascript 更改 CSS?
- sql - 找出历史上每天开放的门票数量
- php - LARAVEL:使用 URL HELPER 方法时从 url 中删除 http
- jhipster - Primeng 与 jhipster
- android - 如何从 CameraX 压缩图像/字节数组
- python - PATH 中的多个 Python 版本
- java - 每次单击按钮时如何将值写入不同的文本字段?
- reactjs - HostFunction 中的异常:来自 JS 的格式错误的调用:字段大小不同 - 问题发生在真实设备上,而不是在模拟器上