Home > database >  How to check if there are two (or more) forward slashes in a string of an Array item with Javascript
How to check if there are two (or more) forward slashes in a string of an Array item with Javascript

Time:05-18

I have below response from a graphql query:

"menu": [{
    "url": ""
  },
  {
    "url": "/"
  },
  {
    "url": "/item/child-item"
  }
]

I need a Boolean variable and check if there is an item in the Array with two (or more) forward slashes /. So it has a child-item in the path like "/item/child-item"

const hasChild = data.menu.map((item) => item.url.includes('// What to do here?'));

CodePudding user response:

The .map() method returns an array, as you're after a boolean, you need to use something different. The .some() method can instead be used, which will return true as soon as the callback you pass it returns true. The .some() will iterate through all of your objects within your array until your callback returns true. You can use the .replace() method to remove any occurrences of characters that are not / and grab the length to check if it appears two or more:

const hasChild = data.menu.some(menuItem => menuItem.url.replace(/[^/]/g, '').length >= 2);

See runnable example below:

const data = {
  "menu": [{
      "url": ""
    },
    {
      "url": "/"
    },
    {
      "url": "/item/child-item"
    }
  ]
};

const hasChild = data.menu.some(menuItem => menuItem.url.replace(/[^/]/g, '').length >= 2);
console.log(hasChild); // true

CodePudding user response:

You do not need map(). map() is when you want to transform an array into another using a function.

You need some(), which returns true if any one of the array items fulfills a condition.

You can use that along with split() to count the number of occurences of a particular character in the string.

const data = { "menu": [
      {
        "url": ""
      },
      {
        "url": "/"
      },
      {
        "url": "/item/child-item"
      }
    ] }

const hasChild = data.menu.some((item) => item.url.split('/').length - 1 > 1);

console.log(hasChild);

In the above code with split(), /a/b/c becomes the array ['','a','b','c']. So you alway get the number of / 1.

CodePudding user response:

You can use Array#some and as for the test, you can split the url by / and if the resulting array has more than 2 elements, then there are at least two / in the string.

const input = {"menu": [ { "url": "" }, { "url": "/" }, { "url": "/item/child-item" } ] },

      output = input.menu.some(({url}) => url.split("/").length > 2);
      
console.log( output );

  • Related