John D
John D

Reputation: 295

how to loop through array that contain objects and check that each value equals null

I am using 16.9.0

I have the below array and i want to check that each object value is equal to null. If that is the case return do something, or just return"Yes".

const data = [
   {0: {country: null}},
   {1: {name: null}},
   {2: {address: null}},
]

what would be the best way to accomplish this?

Sorry for the question but i am coming from a python background.

Any help would be very helpful.

Upvotes: 1

Views: 1092

Answers (4)

Dipankar Maikap
Dipankar Maikap

Reputation: 477

const data = [
   {0: {country: null}},
   {1: {name: null}},
   {2: {address: null}},
   {3: {address: "INDIA"}},
]
data.map((item,index)=>{
let varOne = item[index]
let key = Object.keys(item[index])[0]
if(varOne[key]===null){
console.log('This proparty is null')

}else{
console.log(varOne[key])
}



})

You can also do it like this.

Upvotes: 0

kind user
kind user

Reputation: 41893

You could use single and simple for loop.

const data = [
   {0: {country: null }},
   {1: {name: null }},
   {2: {address: null }},
];

const isEveryNull = (arr) => {
   for (let i = 0; i < data.length; i++) {
      if (Object.values(arr[i][i]).some((q) => q !== null)) return false;
   }
   
   return true;
};

console.log(isEveryNull(data));

Upvotes: 0

yesIamFaded
yesIamFaded

Reputation: 2068

You should check out javascript .map() Funktion for Arrays

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Then just use an If statement to your needs.

Upvotes: 0

Derek Wang
Derek Wang

Reputation: 10193

Using Array.prototype.every function, you can check if all values are null or not.

const data = [
  { 0: { country: null } },
  { 1: { name: null } },
  { 2: { address: null } },
];

const result = data.every((item) =>
  (Object.values(item).every((subItem) =>
    (Object.values(subItem).every(nodeItem => nodeItem == null)))
  )
);
console.log(result);

Upvotes: 2

Related Questions