PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 28, 2022

[FIXED] How to check any every array object property empty or not?

 October 28, 2022     ecmascript-6, is-empty, javascript, lodash     No comments   

Issue

The purpose of function is to get false when all answers are empty. Currently, some how getting **false when only one single answers empty and rest have data inside.

what is the best way to check all answers are empty or not. It doesn't matter some has data and some doesn't. I just wanna see all empty or not.

const questions = [{
    "answers": [{
        "value": "Browns",
        "selected": false,
      },
      {
        "value": "Oranges",
        "selected": false,
      },
      {
        "value": "Purples",
        "selected": false,
      }
    ],
    "info": "",
    "type": "DESELECT",
    "lastUpdated": "2021-11-01T22:50:28.359"
  },
  {
    "answers": [],
    "info": "",
    "type": "DESELECT",
    "lastUpdated": "2021-11-01T22:50:35.392"
  },
  {
    "answers": [{
        "value": "AnimalPrints",
        "selected": false,
      },
      {
        "value": "BigLogos",
        "selected": true,
      },
      {
        "value": "Floral",
        "selected": false,
      }
    ],
    "info": "",
    "type": "DESELECT",
    "lastUpdated": "2021-11-01T22:50:43.883"
  }
];

console.clear();
console.log("------------ES6------------");
const es6Result = questions.every((item) => !_.isEmpty(item.answers));
console.log(es6Result);

const lodashResult = _.every(questions, !_.isEmpty('answers'));
console.log("------------Lodash------------");
console.log(lodashResult);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>


Solution

You could use .some(), you will get true if at least 1 answers is not empty, and you will get false if all answers are empty

const es6Result = questions.some((item) => item.answers.length);


Answered By - Georgy
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing