最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - compare JS objects with values null and empty string - Stack Overflow

programmeradmin2浏览0评论

How can I pare these below two JavaScript objects to be equal and true

var obj1 = {
  'a': 'something',
  'b': null
};
var obj2 = {
  'a': 'something',
  'b': ''
}

var isTrue = _.isEqual(obj1, obj2);

alert(isTrue);
<script src="/[email protected]/lodash.min.js"></script>

How can I pare these below two JavaScript objects to be equal and true

var obj1 = {
  'a': 'something',
  'b': null
};
var obj2 = {
  'a': 'something',
  'b': ''
}

var isTrue = _.isEqual(obj1, obj2);

alert(isTrue);
<script src="https://cdn.jsdelivr/npm/[email protected]/lodash.min.js"></script>

Share Improve this question edited Nov 5, 2019 at 19:44 Ori Drori 193k32 gold badges238 silver badges229 bronze badges asked Nov 5, 2019 at 19:38 imPKimPK 8842 gold badges9 silver badges34 bronze badges 1
  • Possible duplicate of How to do a deep parison between 2 objects with lodash? – nircraft Commented Nov 5, 2019 at 19:41
Add a ment  | 

2 Answers 2

Reset to default 9

You can use _.isEqualWith() and create a custom predicate to handle this case:

var obj1 = {
  'a': 'something',
  'b': null
};
var obj2 = {
  'a': 'something',
  'b': ''
}

var isTrue = _.isEqualWith(obj1, obj2, (a, b) => {
  // if both are null or equal to an empty string then they are equal
  if((_.isNull(a) || a === '') && (_.isNull(b) || b === '')) return true;
});

console.log(isTrue);
<script src="https://cdn.jsdelivr/npm/[email protected]/lodash.min.js"></script>

In theory, they are not equals. '' !== null.
What you could do, is change every empty value to be null first, an then pare them.

var obj1 = {
  'a': 'something',
  'b': null
};
var obj2 = {
  'a': 'something',
  'b': ''
}



var isTrue = _.isEqual(mapEmptyValueToNull(obj1), mapEmptyValueToNull(obj2));
console.log(isTrue);

// we change every value of '' to null.
function mapEmptyValueToNull(object) {
  Object.keys(object).forEach((key) => {
    if(object[key] === '') {
      object[key] = null;
    }
  });
  return object;
}
<script src="https://cdn.jsdelivr/npm/[email protected]/lodash.min.js"></script>

发布评论

评论列表(0)

  1. 暂无评论