6

I need to replace imagesrc with the value stored in this object. However when I run:

if(data['results'][res]['entities']['media']["0"]["media_url"]) {
    imagesrc = data['results'][res]['entities']['media']["0"]["media_url"];
}

I get the error:

Cannot read property '0' of undefined

How can I run my condition so that I don't get errors if something is undefined?

Colin Brock
  • 21,267
  • 9
  • 46
  • 61
lisovaccaro
  • 32,502
  • 98
  • 258
  • 410

5 Answers5

5
if (data['results'][res]['entities']['media']["0"] == undefined
    || data['results'][res]['entities']['media']["0"] == null) {

    ...
}
Web User
  • 7,438
  • 14
  • 64
  • 92
  • You don't need `... == undefined || ... == null`. Just do one or the other since `==` will return `true` in both cases. –  Jan 18 '12 at 19:45
  • 1
    `try catch` may be better doing this for every variable make the code looks ugly. – Krishnadas PC Jul 09 '18 at 06:27
3

you can place your code inside a try catch block and examin error message.

Arian
  • 12,793
  • 66
  • 176
  • 300
1

I’m a fan of using short circuit evaluation for these kinds of situations:

items && items[val] && doSomething(items[val])

Some people might be repulsed by this, but I think it’s a nice and readable way to express something that should only be evaluated if certain conditions are met.

In this case, we’re actually chaining two short circuit evaluations. First, we determine whether items has a defined value. If it undefined, then the rest of the expression is moot, so we won’t even bother to evaluate it. AND if it is defined, then let’s check for the existence of some property that we’re interested in. If it’s undefined, then bail out. AND if it’s true, we can go ahead and evaluate the rest of the expression.

I think it’s a lot easier to reason through at a glance than:

if (items) {
   if (items[val]) {
     doSomething(items[val])
   }
}

Ternary operators work similarly:

 items 
     ? items[val] 
         ? doSomething(items[val])
         :  alert(‘The property “‘ + val + ‘“ has not yet been defined.’)
     : alert(‘You have not yet defined any items!’)
Rob
  • 159
  • 1
  • 10
1

You could write a function that walks the object tree and returns undefined as soon as it hits an undefined property:

function safeGetData(obj, names)
{
    for (var i = 0; i < names.length; ++i) {
        if (typeof obj === "undefined") {
            return undefined;
        }
        obj = obj[names[i]];
    }
    return obj;
}

You can use it like this:

var imagesrc = safeGetData(data,
    ["results", res, "entities", "media", "0", "media_url"]);
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
0

It's an old topic, I know. It's just to add my 2 cents. I'm definitely not a javascript "guru", but here's one of my old attempts. It relies upon a couple of new ecmascript 6 features and it's going to approach the problem in a more "functional" way:

const prop = (...arr) => obj => arr.reduce((acc, v) => acc && acc.hasOwnProperty(v) ? acc[v] : undefined, obj)

And some tests in order to show how it should work:

describe('unit - prop', () => {
    const event = {
            record: {
                sns: {
                    subject: 'Hello',
                    message: '<div>Welcome!</div>'
                }
            }
        }

    it('property exists', done => {
        const value = prop('record', 'sns', 'subject')(event)
        expect(value)
            .to
            .be
            .equal('Hello')
        done()
    })

    it('property does not exist', done => {
        const value = prop('record', 'bad', 'subject')(event)
        expect(value)
            .to
            .be
            .undefined
        done()
    })
})

Does it make sense?

NicolaBaldi
  • 133
  • 1
  • 2
  • 6