I have an array of objects as below :
var data = [{country:"Austria", "customer name":"tech comp", order:"123"},
{country:"China", "customer name":"hk", order:"1111"},
{country:"UK", "customer name":"dev tech", order:"22"},
{country:"United State", "customer name":"technology", order:null} ];
I want to loop through each property, check the longest string and return number of characters.
For expample : on the property country, United State is the longest string among Austria, China and Uk so we return its length which is 12.
The same for other properties customer name and order.
The problem is when a property has null value. I receive the error Cannot read property 'length' of null"
I tried adding x => x[key].length || 0 so it should count length if not then 0 but not working.
Also inside the map I added an if block if (x[key] != null) { x => x[key].length } else { x => 0 ; } but not working.
Any suggestions please how can add a condition for example if the value is null then the default length is 0 so that my code could work properly ? Thank you very much.
var data = [
{country:"Austria", "customer name":"tech comp", order:"123"},
{country:"China", "customer name":"hk", order:"1111"},
{country:"UK", "customer name":"dev tech", order:"22"},
{country:"United State", "customer name":"technology", order:null} ];
const longestValue = (key, array) => Math.max(...array.map(x => x[key].length));
$.each(data[0], function(key){
console.log(key);
console.log(longestValue(key, data));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>