Puerto
Puerto

Reputation: 1134

Add a default value for a json property when it doesn't exist in Javascript

So I'm trying to edit this rss feed with these 2 functions because of the media:content property which I have had no luck accessing directly. the functions I have below work for creating a new value called mediaContent which I can then easily access. The issue is in the rss feed not all objects will have media:content and I want to add a default value for the objects that don't have that property so I have consistency in my objects. Otherwise I end up with undefined on on some of mediaContent in my new object. I wanted to start just added a default value in when media:content is not present in the object but these ||'s are not working as I would have expected. How can I get my else if to punch in a default value if media:content does not exist? I'm probably missing something easy.

function getMediaContent(value) {
    for (var i in value) {
        if (i === "media:content") {
            console.log("MC::", i)
            return value[i].$;
        } else if (i !== "title" || i !== "link" || i !== "pubDate" || i !== "isoDate" || i !== "guid" || i !== "contentSnippet" || i !== "content") {
            debugger;
            return "no media content"
        }
    }
}

function getNewsLinks() {
    return newsItems.map(value => ({
        value,
        mediaContent: getMediaContent(value)
    }))
}

SOLUTION (based on accepted answer)

    function getMediaContent(value) {
        return "media:content" in value ? value["media:content"].$ : "no media content";

    }

works perfectly. Thanks!

Upvotes: 0

Views: 2716

Answers (2)

keremy
keremy

Reputation: 11

I needed something similar and optionally it would work for multi-layered JSON objects. Here is the function I use:

function getFromJSON(obj, ...args) {
    for (const arg of args) {
        if (!Array.isArray(arg)) {
            if (arg in obj) {
                obj = obj[arg]
            } else {
                return `${arg} not found in JSON`;
            }
        } else {
            for (const argOpt of arg) {
                if (argOpt in obj) {
                    obj = obj[argOpt]
                    break;
                }
            }
        }
    }
    return obj
}

In addition, you can pass multiple keys in an array if you want to get the value of whichever exists.

Upvotes: 1

Heretic Monkey
Heretic Monkey

Reputation: 12114

Since you're just looking to see if a property exists on an object, you can use the in operator:

function getMediaContent(value) {
  return "media:content" in value ? value["media:content"].$ : "no media content";
}

That checks if the property exists, and if so, gets the value of its $ property. Otherwise, returns the default value.

Upvotes: 2

Related Questions