Search code examples
javascriptloopsjavascript-objects

How to know if an array contains an object with a certain 'key'?


Let's say I have this data structure wherein I have an array that contains a set of objects, the objects being 'months'.

monthlySum: [
  {
              jun2018: {
                sales: 0,
                expenses: 0
              } 
            },
            {
              aug2018: {
                sales: 0,
                expenses: 0
              } 
            }
          ]

Now I'd like to know, let's say, if an object with a key of 'sep2018' already exists in this array. If not yet, then I will add a new object with the 'sep2018' key after the last one. If yes, then I will do nothing.

How do I go about doing this?



Solution

  • For an update or check, you could use Array#find, which returns either the item or undefined if not found.

    function find(array, key) {
        return array.find(object => key in object);
    }
    
    var monthlySum = [{ jun2018: { sales: 0, expenses: 0 } }, { aug2018: { sales: 0, expenses: 0 } }];
    
    console.log(find(monthlySum, 'aug2018'));
    console.log(find(monthlySum, 'dec2018'));