问题描述
我有 2 个 json 对象。
第一个保存来自客户端表单的数据。
{
"name": "Example name","company": {
"name": "new company","size": "FIVE","licenseInfo": {
"isActive": "0"
}
}
}
在我的另一个对象中,我知道在此表单中修改了哪些字段。如果 value 为 true,则它已更改。我使用的插件为我提供了这些信息。
{
"name": true,"company": {
"size": true,"licenseInfo": {
"isActive": true
}
}
}
我想比较这 2 个对象并获得一个仅包含更改数据的提交对象,如下所示。 公司名称未更改,我不想提交 company.name
{
"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));