javascriptarraysjsonsearch

Searching in array that contains multiple objects on the basis of key's value


I am trying to search for the total no. of occurrence of a value in an array on the basis of key. I have already tried it using loop, which gave the correct answer. Is there any other suitable way?

If I have array which conatins repeated type:'page_title' given as below:

  weddingData: Array<WeddingDataModel> = [
{
  type: 'page_title',
  data: {
    title: 'Hello First element',
  }
},
 {
  type: 'page_title',
  data: {
    title: 'Hello Second Element',
  }
},
 {
  type: 'page_title',
  data: {
    title: 'Hello Third Element',
  }
},
 {
  type: 'page_title',
  data: {
    title: 'Hello',
  }
},
{
  type: 'background_color',
  data: {
    backgroundColor: '#ff785'
  }
},
{
  type: 'banner_images',
  data: {
    image1 : {},
    image2: {},
    image3: {}
  }
}];

Now, how can I get the no. of count(s) of key 'page-title' present in weddingData array


Solution

  • May be you can use filter (javascript version):

    var weddingData = [
    {
      type: 'page_title',
      data: {
        title: 'Hello First element',
      }
    },
     {
      type: 'page_title',
      data: {
        title: 'Hello Second Element',
      }
    },
     {
      type: 'page_title',
      data: {
        title: 'Hello Third Element',
      }
    },
     {
      type: 'page_title',
      data: {
        title: 'Hello',
      }
    },
    {
      type: 'background_color',
      data: {
        backgroundColor: '#ff785'
      }
    },
    {
      type: 'banner_images',
      data: {
        image1 : {},
        image2: {},
        image3: {}
      }
    }];
    
    console.log(weddingData.filter(x => x.type === 'page_title').length)