shoegazer
shoegazer

Reputation: 54

How to display a property value based on another property value of a JSON object?

I have a JSON that contains objects where each has "href" and "message" properties. If the URL matches the href, the corresponding message should appear in the console log. So if the URL has "apples" in it, it should console log the word "Yes!"

This is what I have so far...

var banner = [
        {
            'href': 'apples',
            'message': 'yes!'
        },
        {
            'href': 'oranges',
            'message': 'no!'
        },
        {
            'href': 'grapes',
            'message': 'maybe!'
        },
    ];

    if (window.location.href.indexOf(banner.name)) {
      console.log(banner.message);
    }

Upvotes: 0

Views: 632

Answers (2)

EduardoSaverin
EduardoSaverin

Reputation: 545

You can filter out data like this

var banner = [
        {
            'href': 'apples',
            'message': 'yes!'
        },
        {
            'href': 'oranges',
            'message': 'no!'
        },
        {
            'href': 'grapes',
            'message': 'maybe!'
        },
    ];

function findFromBannerData(query) {
    filterData = banner.filter(item => {
      if (item.href === query) {
        return true;
      }
      return false;
    });
    return filterData;
}
console.log(findFromBannerData('oranges'));

If the returned value from function is not empty array then it has the value you need means Yes!

Edited Answer :

if (window.location.href && banner) {
    let result = banner.find(item => window.location.href.includes(item.href))
    if (result) {
        console.log(result.message)
    }
}

Upvotes: 1

DecPK
DecPK

Reputation: 25406

You can replace href with any string. Just find the element if the href exist in any of the objects in the banner object.

const href = window.location.href;

or

const result = banner.find((o) => window.location.href.includes(o.href));

var banner = [{
    href: "apples",
    message: "yes!",
  },
  {
    href: "oranges",
    message: "no!",
  },
  {
    href: "grapes",
    message: "maybe!",
  },
];

const href = "www.grapes.com";

const result = banner.find((o) => href.includes(o.href));
if (result) {
  console.log("Yes")
}

Upvotes: 1

Related Questions