0

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?


2
  • 1
    maybe you consider to use a different data struncture, like an object, instead of an array because you have already grouped by decent key. Commented Jun 10, 2018 at 7:52
  • @NinaScholz Yeah I was also considering that.. Commented Jun 10, 2018 at 8:03

2 Answers 2

1

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

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

Comments

1

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

Comments

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.