skip to Main Content

I have the following sample data

var array=[
    {
        "id": null,
        "name": 1251,
        "department": null,
        "DOB":null
    },
    {
        "id": null,
        "name": null,
        "department": 48,
        "DOB":null
    },
    {
        "id": 1421452,
        "name": null,
        "department": 0,
        "DOB":null
    },
    {
        "id": null,
        "name": 1251,
        "department": null,
        "DOB":null
    }
]
    

Requirement is to find first non-null value of each property in the object. For example need to fetch the first non null value of property name in the entire array of objects and it should return 1251 as it is the first non null and not a zero value. In case if all the property values are null like DOB, need to return null.If all values are mix of null and 0 need to return 0
I tried using

var non_null=array.find(el.age=>el.age!=null);

But it throws error

5

Answers


  1. Iterate through every object and through each key, and you can create different checks depending on what you want to return based on the value.

    var array=[
        {
            "id": null,
            "name": 1251,
            "department": null,
            "DOB":null
        },
        {
            "id": null,
            "name": null,
            "department": 48,
            "DOB":null
        },
        {
            "id": 1421452,
            "name": null,
            "department": 0,
            "DOB":null
        },
        {
            "id": null,
            "name": 1251,
            "department": null,
            "DOB":null
        }
    ]
    
    array.forEach(obj => {
        for (const key in obj) {
            if(obj[key]) {
                console.log(obj[key])
            }
        }
    })
    Login or Signup to reply.
  2. As pointed out by RDU, you need to iterate the keys of the elements, then assign their corresponding values to a record. The assignment can be done in one line using the nullish coalescing assignment:

    function getFirstNonNullKeyValuePairs(array) {
      const record = {};
    
      // For each element
      for (const element of array) {
        // For each key
        for (const key in element) {
          // If the recorded value is not nullish (i.e. undefined or null),
          // this will be ignored.
          // Otherwise, add the corresponding value to the record.
          record[key] ??= element[key];
        }
      }
    
      return record;
    }
    

    Try it (terser version):

    function getFirstNonNullKeyValuePairs(array) {
      return array.reduce(
        (record, element) => Object.entries(element).reduce(
          (record, [key, value]) => (
            record[key] ??= value,
            record
          ),
          record
        ), {}
      );
    }
    
    const array = [
      {
        id: false,
        name: null,
        department: null,
        DOB: null
      },
      {
        id: null,
        name: '',
        department: null,
        DOB: null
      },
      {
        id: null,
        name: null,
        department: 0,
        DOB: null
      },
      {
        id: null,
        name: null,
        department: null,
        DOB: null
      }
    ];
    
    console.config({
      maximize: true
    });
    
    console.log(array);
    console.log(getFirstNonNullKeyValuePairs(array));
    <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
    Login or Signup to reply.
  3. On your array you can play with the returns:

    const checkFirstNotNull = (arr) =>{
    
      for(let i=0; i<arr.length;i++){
        if(arr[i].age){
          return arr[i]; //or return true or whatever you want^^
        }
      }
      return; //false or whatever you want once again^^
    }
    

    The advantage here is that the default return is the last one which won’t be triggered since the first return in the for loop will stop the function

    Login or Signup to reply.
  4. "Requirement is to find first non-null value of each property in the object"
    Assuming that the object is the entire array, i would loop over the keys of the objects in the array. Then, for each key, do a find on the array.
    (Different is if you want for each object of the array, and for each key the first not null value)

    Then, the find method returns the first element which that property is not null or not equal to 0 (even empty string '' or false). To get the property value you have to do dynamic property access like this element[name].
    I’ve added the bucket and buckets array just to get a clearer example.

    const array = [
        {
            "id": 0,
            "name": 1251,
            "department": null,
            "DOB":null
        },
        {
            "id": null,
            "name": null,
            "department": 48,
            "DOB":null
        },
        {
            "id": 1421452,
            "name": null,
            "department": 0,
            "DOB":null
        },
        {
            "id": null,
            "name": 1251,
            "department": null,
            "DOB":null
        }
    ];
    
    const prop = new Set(['id', 'name', 'department', 'DOB'])
    
    const buckets = []
    for (const name of prop) {
        
        const element = array.find(el => el[name]);
        // object destructuring and nullish coalescing operator ??
        // this is for the DOB property, whose find returns null and we have to handle it
        const { [name]: value  } = element ?? {};
        const bucket = {
            value: value,
            key: name,
            objRef: element,
        }
    
        buckets.push(bucket)
    }
    
    console.log(buckets)
    Login or Signup to reply.
  5. Use the find method along with the Boolean function to find the first non-null or non-zero value of a property in an array of objects:

    const array = [
      { id: 1, value: null },
      { id: 2, value: 0 },
      { id: 3, value: 5 },
      { id: 4, value: '' },
      { id: 5, value: 'Hello' },
    ];
    
    const result = array.find((obj) => Boolean(obj.value));
    console.log(result); // { id: 3, value: 5 }
    

    The find method searches through the array and returns the first object where the value property is non-null and non-zero. The Boolean function is used to check whether the value of the property is truthy. If the find method does not find any matching objects, it returns undefined.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search