1

I am trying to exclude items that contain Packages in packageData.type. To show only the packageData that has items with packageData.type as Add-on.

Array is as example

{
  "packageData": [
    {
      "title": "Title 1",
      "type": [
        "Packages"
      ]
    },
    {
      "title": "Title 2",
      "type": [
        "Add-on"
      ]
    },
    {
      "title": "Title 3",
      "type": [
        "Add-on"
      ]
    },
    {
      "title": "Title 4",
      "type": [
        "Add-on"
      ]
    }
  ]
}

and this is how I am currently trying to remove results which is giving zero results.

<ul>
  {packageData.map(function() {
    if (packageData.type ==! "Packages") {
     return (
      <li key={packageData.id}>
        <a>
          <img src={packageData.heroImage.sizes.src} alt=""/>
          <h3>{packageData.title}</h3>
        </a>
      </li> );
    } else {
      return null;
    };
  })}
</ul>

How can I make this work? Or should I be filtering these results prior to displaying and then map the returned items?

5
  • Array.prototype.filter() Commented Jun 20, 2018 at 7:54
  • Why not just use filter? It returns an array as well. Commented Jun 20, 2018 at 7:55
  • You can simply use the javascript's filter prototype Commented Jun 20, 2018 at 7:55
  • 1
    Your type property contains an array. Comparing a string to an array will never yield true. Commented Jun 20, 2018 at 7:57
  • Thank you all - there I was over complicating things. My array is slightly more complex than the example shown but you've put me on the right path. Commented Jun 20, 2018 at 7:59

1 Answer 1

4

You have to use filter before map, Filter will filter the array and then map will iterate through array. Below is the sample code

var data = {
  "packageData": [
    {
      "title": "Title 1",
      "type": [
        "Packages"
      ]
    },
    {
      "title": "Title 2",
      "type": [
        "Add-on"
      ]
    },
    {
      "title": "Title 3",
      "type": [
        "Add-on"
      ]
    },
    {
      "title": "Title 4",
      "type": [
        "Add-on"
      ]
    }
  ]
};

data.packageData.filter((item) => { return item.type[0] !== 'Packages' }).map((item)=> { console.log(item); });

Sign up to request clarification or add additional context in comments.

1 Comment

OP says he specifically wants only the Add-On types to be shown rather than "not Packages". If another type is added, this code will break - you should instead check that item.type.indexOf("Add-On") !== -1

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.