如何以更易读的方式执行以下操作?:
if (nextProps.a !== this.props.a ||
nextProps.b !== this.props.b ||
nextProps.cc !== this.props.cc ||
nextProps.d !== this.props.d){
}
请注意,有问题的对象有更多属性,只有a,b,cc和d,但我只想比较这些属性。我使用的是ES6。
答案 0 :(得分:1)
尝试这样的事情
isOk = true;
props = ["a","b","cc","d"]; //replace this with whatever your properties are from
for(i in props){
if(nextProps[i]==this.props[i]){
isOk = false;
break;
}
}
if(isOk){
// :)
}
答案 1 :(得分:0)
var names = Object.getOwnPropertyNames(nextProps);
var result = false;
for (var i = 0; i < names.length; i++) {
result = nextProps[names[i]] !== this.props[name[i]];
if (result)
break;
}
if (result) {
// ...
}
答案 2 :(得分:0)
我会写一个方法:
// Comparison of all properties equal
function propsEqual(obj1, obj2, props) {
var equal = true;
var propsLen = props.len;
while(propsLen-- && equal) {
var prop = props[propLen];
equal = obj1[prop] === obj2[prop];
}
return equal;
}
// Comparison of any properties equal
function anyPropsEqual(obj1, obj2, props) {
var equal = false;
var propsLen = props.len;
while(propsLen-- && !equal) {
var prop = props[propLen];
equal = obj1[prop] === obj2[prop];
}
return equal;
}
&#13;
答案 3 :(得分:0)
使用List.some:
["orgId","roleId","userGroupId","userId"].some( v => a[v] !== b[v])
let a = {orgId: 1,roleId:2, userGroupId:3, userId:4};
let b = {orgId: 1,roleId:2, userGroupId:3, userId:4};
console.log(["orgId","roleId","userGroupId","userId"].some( v => a[v] !== b[v]));
a = {orgId: 1,roleId:2, userGroupId:3, userId:5};
b = {orgId: 1,roleId:2, userGroupId:3, userId:4};
console.log(["orgId","roleId","userGroupId","userId"].some( v => a[v] !== b[v]));
a = {orgId: 1,roleId:2, userGroupId:3, userId:4};
b = {orgId: 2,roleId:2, userGroupId:3, userId:4};
console.log(["orgId","roleId","userGroupId","userId"].some( v => a[v] !== b[v]));