skip to Main Content
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.
Thank you

2

Answers


  1. With regular JS:

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

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

    Object.entries(x).map(([k, v]) => v === undefined).filter(Boolean).length
    

    With Lodash

    _.filter(x, (v, k) => v === undefined).length
    
    Login or Signup to reply.
  2. 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:

    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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search