catandmouse
catandmouse

Reputation: 11809

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?


Upvotes: 0

Views: 67

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386560

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'));

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370679

You can use .some to check to see if anything in an array passes a certain test:

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

if (!monthlySum.some((obj) => 'aug2018' in obj)) {
  monthlySum.push({
    aug2018: {
      sales: 0,
      expenses: 0
    }
  })
}
if (!monthlySum.some((obj) => 'sep2018' in obj)) {
  monthlySum.push({
    sep2018: {
      sales: 0,
      expenses: 0
    }
  })
}
console.log(monthlySum);

Upvotes: 1

Related Questions