1

I'm trying to use normalize-url in my code here:

The socialfields is an object I converted to an array using the for...of loop. The value of the socialfields keys are URL to social medias e.g:

{
  youtube: 'youtube.com/peoray',
  facebook: 'facebook.com/peoray',
  twitter: 'twitter.com/peoray',
}

So I'm trying use normalize-url on the links. But it's not working. The error I'm getting is that TypeError: Cannot read property 'length' of undefined.

Here is the code:

for (const [key, value] of Object.entries(socialfields)) {
    if (value.length > 0)
        socialfields[key] = normalize(value, {
            forceHttps: true
        });
}
11
  • 1
    apparently one of the social media urls is null. It means the value will be null and null.length is an Error. Commented Feb 28, 2020 at 23:31
  • I don't understand. What do you mean it will be null. Sorry for my noob question Commented Feb 28, 2020 at 23:32
  • 1
    You shouldn't have to do if (value.length > 0) - the following should be fine: if (value) or if you really wanted if (value && value.length > 0) - this is happening because the .length property does not exist on a null object/variable. Commented Feb 28, 2020 at 23:34
  • 2
    print the socialfields object right before the for loop. My guess is that you have an entry like this pinterest: null Commented Feb 28, 2020 at 23:34
  • 1
    Is if (value) not clean enough? That's all you need.... Commented Feb 28, 2020 at 23:39

1 Answer 1

1

You shouldn't have to do if (value.length > 0) - the following should be fine: if (value) or if you really wanted if (value && value.length > 0) - this is happening because the .length property does not exist on a null object/variable.

This is all you should have to do:

for (const [key, value] of Object.entries(socialfields)) {
  if (value) socialfields[key] = normalize(value, { forceHttps: true });
}

If you wanted to get 'fancy' you could use the ternary operator.. I still think the if (value) ... is the best way to go about it.

for (const [key, value] of Object.entries(socialfields)) {
  value ? socialfields[key] = normalize(value, { forceHttps: true }) : '';
}
Sign up to request clarification or add additional context in comments.

2 Comments

Not sure about the second option. VSCode threw an error ';' expected.ts(1005)
Yea I removed it, I forgot you couldn't use it before an assignment.

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.