英文:
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 = { "name": undefined, "value": "tr", "prop1": undefined, "prop2": "test", "prop3": 123 };
const counts = _.countBy(data);
console.log(counts);
console.log(counts.undefined);
<!-- language: lang-html -->
<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>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论