Peoray
Peoray

Reputation: 1905

How to get the value of an object using for of loop

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
        });
}

Upvotes: 1

Views: 106

Answers (1)

Matt Oestreich
Matt Oestreich

Reputation: 8528

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 }) : '';
}

Upvotes: 1

Related Questions