0

I want to push object into array if it is defined else push '0'

I am sending count object into count array.

var emptyObj = { 'cnt': 0 };

countArr.push(matchCdnCnt !== 'undefined' ? matchCdnCnt : emptyObj.cnt);
countArr.push(matchInvCnt !== 'undefined' ? matchInvCnt : emptyObj.cnt);
countArr.push(mismatchInvCnt !== 'undefined' ? mismatchInvCnt : emptyObj.cnt);
countArr.push(mismatchCdnCnt !== 'undefined' ? mismatchCdnCnt : emptyObj.cnt);
countArr.push(onHoldInvCnt !== 'undefined' ? onHoldInvCnt : emptyObj.cnt);
countArr.push(onHoldCdnCnt !== 'undefined' ? onHoldCdnCnt : emptyObj.cnt);
countArr.push(availgstnInvCnt !== 'undefined' ? availgstnInvCnt : emptyObj.cnt);
countArr.push(availgstnCdnCnt !== 'undefined' ? availgstnCdnCnt : emptyObj.cnt);
countArr.push(pendingInvCnt !== 'undefined' ? pendingInvCnt : emptyObj.cnt);
countArr.push(pendingCdnCnt !== 'undefined' ? pendingCdnCnt : emptyObj.cnt);

I wants to push count object or 0.

4
  • 2
    'undefined' and undefined are not the same. Commented Aug 27, 2019 at 9:01
  • you can use countArr.push(matchCdnCnt || emptyObj.cnt) Commented Aug 27, 2019 at 9:06
  • @AZ_ And what if value is some other falsy value ? Commented Aug 27, 2019 at 9:19
  • ahh missed that, thanks @prsvr. will have to use ternary. Commented Aug 27, 2019 at 9:21

3 Answers 3

1

You achieve this with only one condition if(cnt), Check below snippet, I take an array of objects to check all cases In which It pushes 0 into an array if cnt is undefined/''/null else it's push value of cnt.

const array = [];
const myObjects = [{ cnt: 3 }, { cnt: 4 }, { cnt: 5 }, { cnt: undefined }, { cnt: '' }, { cnt: null }];

myObjects.forEach((m) => {
  const { cnt } = m;
  const pushElement = cnt || 0;
  array.push(pushElement);
});

console.log(array); 

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

Comments

0

You can do something like this:

let emptyObj = { 'cnt': 3 };
let undefinedObj;

let array = [
  emptyObj && emptyObj.cnt ? emptyObj.cnt : 0,
  undefinedObj ? undefinedObj: 0
];

console.log(array)

The emptyObj && emptyObj.cnt ? emptyObj.cnt : 0 doesn't only validates "undefined" objects but also nulls objects.

Comments

0

I found another solution where it will assign count 0 if required count variable return undefined else cnt value as below

    countArr.push(typeof matchCdnCnt!= 'undefined'? matchCdnCnt.cnt: emptyObj.cnt);
    countArr.push(typeof matchInvCnt!= 'undefined'? matchInvCnt.cnt: emptyObj.cnt);

I have to do so much after this result.

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.