使用Lodash找到对象中未定义属性的数量。

huangapple go评论84阅读模式
英文:

Find the number of undefined properties in an object with Lodash

问题

我需要找出未定义的属性数量,在这种情况下是2。

英文:
let x =    {
      "name": undefined,
      "value": "tr",
      "prop1": undefined,
      "prop2": "test",
      "prop3": 123
    };

I need to find the number of properties that are undefined, so in this case 2.

答案1

得分: 0

使用常规的JS:

好的评论指出,我们确实可以立即进行过滤;更高效的方法是:

Object.values(x).filter(v => v === undefined).length

使用Lodash

_.filter(x, (v, k) => v === undefined).length
英文:

With regular JS:

Good comments pointed out that we can indeed immediately filter; more efficient:

Object.values(x).filter(v=> v === undefined).length

With Lodash

_.filter(x, (v, k) => v === undefined).length

答案2

得分: 0

你可以使用 _.countBy() 来获得一个包含值在原始对象 (data) 中出现次数的对象 (counts)。然后,你可以从 counts 对象中获取 undefined 值的数量:

const data = { "name": undefined, "value": "tr", "prop1": undefined, "prop2": "test", "prop3": 123 };

const counts = _.countBy(data);

console.log(counts);

console.log(counts.undefined);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
英文:

You can use _.countBy() to get an object (counts) that contains the number of time a value appears in the the original object (data). You can then get the number of undefined values from the counts object:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const data = { &quot;name&quot;: undefined, &quot;value&quot;: &quot;tr&quot;, &quot;prop1&quot;: undefined, &quot;prop2&quot;: &quot;test&quot;, &quot;prop3&quot;: 123 };

const counts = _.countBy(data);

console.log(counts);

console.log(counts.undefined);

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js&quot; integrity=&quot;sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==&quot; crossorigin=&quot;anonymous&quot; referrerpolicy=&quot;no-referrer&quot;&gt;&lt;/script&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月28日 05:38:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76783544.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定