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
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.
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:
Try it (terser version):
On your array you can play with the returns:
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
"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
''
orfalse
). To get the property value you have to dodynamic property access
like thiselement[name]
.I’ve added the bucket and buckets array just to get a clearer example.
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:
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.