Javascript json对象如何将更改后的数据移动到新对象



我有2个json对象。

第一个保存来自客户端表单的数据

{
"name": "Example name",
"company": {
"name": "new company",
"size": "FIVE",
"licenseInfo": {
"isActive": "0"
}
}
}

在我的另一个对象中,我知道哪些字段是以这种形式修改的。如果值为true,则它已经更改。我使用的插件提供了这些信息。

{
"name": true,
"company": { 
"size": true,
"licenseInfo": {
"isActive": true
}
}
}

我想比较这两个对象,得到一个只有更改数据的提交对象,如下所示。公司名称没有更改,我不想提交公司名称

{
"name": "Example name",
"company": { 
"size": "FIVE",
"licenseInfo": {
"isActive": "0"
}
}
}

我可以一个接一个地手动控制字段,但我想创建一个动态比较函数,这样我就可以在其他表单上使用它。

按键迭代(比较(并添加输入值。。。

const input = { "name": "Example name", "company": { "name": "new company", "size": "FIVE", "licenseInfo": { "isActive": "0" } } }
const compare = { "name": true, "company": { "size": true, "licenseInfo": { "isActive": true } } }
function filter(input, compare) {
const output = {};
for (const key in compare)
output[key] = typeof compare[key] == "object"
? filter(input[key], compare[key])
: input[key];
return output;
}
console.log(filter(input, compare));

最新更新