0

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>

2 Answers 2

2

try

const longestValue = (key, array) => Math.max(...array.map(x => x[key]?.length || 0));

Sign up to request clarification or add additional context in comments.

Comments

1

You can try to coerce a truthy value of your map query here with this:

...array.map(x => x[key] && x[key].length)

This should first check if x[key] is true/has a length and then return false if not. This should prevent the error from being thrown.

A classic if (x[key]) { ....} where you return if x[key] has a falsy value would also work but is a bit ugly inside of a map.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.