skip to Main Content

I have many javascript objects which are like:

{
  "id": "123",
  "name": undefined,
  "other": undefined,
  "and": "so on",
  ... and many others, each time different fields
}

But most of the time the fields can be all undefined except id (which is always != undefined).

I would like a method to detect if an object has AT LEAST ONE valued prop BESIDES "id".

What do you recommend?

2

Answers


  1. you can use Object.entries and some

    const a = {
      "id": "123",
      "name": undefined,
      "other": undefined,
      "and": "so on",  
    }
    
    const b = {
      "id": "123",
      "name": undefined,
      "other": "bla",
      "and":  "bla",  
    }
    
    const c = {
      "id": "123",
      "name": undefined,
      "other": undefined,
      "and":  undefined,  
    }
    
    const hasValue = obj => Object.entries(obj).some(([k,v]) => k!=='id' && v!==undefined)
    
    console.log(hasValue(a))
    console.log(hasValue(b))
    console.log(hasValue(c))
    Login or Signup to reply.
  2. We can use for in loop. In the loop we put condition that key can’t be id and other keys cannot be undefined. For Example :

    function detectTwoValuedProperty(obj) {
      for (let key in obj) {
        if (key !== "id" && obj[key] !== undefined) {
          return true;
        }
      }
      return false;
    }
    
    const objectOne = {
      "id": "123",
      "name": undefined,
      "other": undefined,
    };
    
    const objectTwo = {
      "id": "456",
      "name": "Fred Hors",
      "age": undefined,
    };
    
    console.log(detectTwoValuedProperty(objectOne)); // return false
    console.log(detectTwoValuedProperty(objectTwo)); // return true
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search