[英]Compare JSON array and JSON object and find Difference
I've one JSON array and JSON object (Which is string) and I wanted to compare and find different field from both.我有一个 JSON 数组和 JSON 对象(它是字符串),我想比较并从两者中找到不同的字段。
I've tried below possibilities and get o/p as:我尝试了以下可能性并得到 o/p 为:
JSON Response is as: JSON 响应如下:
-------rule_before RowDataPacket { id: 75, input: 'day_of_week', input_data: '0,1', condition: 'in', status: 'active', extra_fields: '' } -------filter_before RowDataPacket { id: 74, when: 'match', output: 'assign_department', output_data: '3,1', output_data_json: '', status: 'active' } -------rule_after { input: 'page_title', input_data: 'Home', extra_fields: '', condition: 'match', status: 'active' } -------filter_after { when: 'match', output: 'assign_agent', output_data: '1', output_data_json: '', status: 'active' }
let rule_before = rule_data; let filter_before = filter_data; let rule_after = JSON.parse(request_data.rules); let filter_after = JSON.parse(request_data.filters); rule_before = rule_before[0]; filter_before = filter_before[0]; rule_after = rule_after[0]; filter_after = filter_after[0]; console.log("\\n-------rule_before\\n", rule_before); console.log("\\n-------filter_before\\n", filter_before); console.log("\\n-------rule_after\\n", rule_after); console.log("\\n-------filter_after\\n", filter_after);
I want the difference like我想要这样的区别
for rule: input: 'day_of_week' => input_data: 'Home' for filter: when: 'match' => when: 'match'对于规则:输入:'day_of_week' => input_data:'Home' for filter:when:'match' => when:'match'
I'm not really sure what you are trying do to but if you want to get all matches of two Objects try the simple function below.我不太确定您要做什么,但是如果您想获得两个对象的所有匹配项,请尝试下面的简单功能。
function diff(obj1, obj2) {
// Check if the Parameters are actually Objects
if (!(typeof(obj1) === "object" || typeof(obj2) === "object"))
return false
// Create arrays out of the Objects
const arr1 = Object.entries(obj1)
const arr2 = Object.entries(obj2)
// Instantiate an array with the matches
let result = []
arr1.forEach(el1 => {
arr2.forEach(el2 => {
// Check if it matches
if (el1[0] === el2[0] && el1[1] === el2[1]) {
// Add the match to the result
result.push(el1[1])
}
})
})
// Return the matches
return result
}
PS: If you have nested Objects this function doesn't work. PS:如果您有嵌套对象,则此功能不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.