Reputation: 439
I am getting error while checking any object has some value from one array using Javascript. I am explaining my code below.
let arr = [
{
"config": "as",
"payload": ""
},
{
"config": "as",
"payload": "xc"
},
{
"config": "",
"payload": "xc"
},
{
"config": "",
"payload": ""
}
]
let isNext = true;
for(let i=0; i < arr.length; i++) {
if(arr[i].config !== '' || arr[i].payload !=='') {
isNext = false
return;
}else{
isNext = true;
}
}
console.log('next', isNext);
Here I have one array of object
and each object has 2 key-value pair
. I need inside array it will check if any one of object has some value for both config
or payload
then isNext
will be false other wise it will be true. but as per this code I am getting the following error.
Uncaught SyntaxError: Illegal return statement"
Please help me to resolve this issue.
Upvotes: 0
Views: 43
Reputation: 481
Your code is strange because you have no result.
Maybe you want to find the first suitable object from your array?
So the code will be:
const arr = [
{
"config": "as",
"payload": ""
},
{
"config": "as",
"payload": "xc"
},
{
"config": "",
"payload": "xc"
},
{
"config": "",
"payload": ""
}
];
let result = null;
let isNext = true;
for(let i=0; i < arr.length; i++) {
if(arr[i].config !== '' || arr[i].payload !=='') {
isNext = false
result = arr[i];
break;
}else{
isNext = true;
}
}
console.log('my result', result);
Or you want to check if any of elements are suitable for your condition you can make:
const result = arr.some(el => el.config || el.payload);
Or you can find and return the first suitable element:
const result = arr.find(el => el.config || el.payload);
Upvotes: 1
Reputation: 212
you shouldn't have a return
statement outside a function scope, if you're trying to escape the for loop use break
instead.
Upvotes: 1
Reputation: 189
In you code you can replace return from break so it will go out from loop once condition satisfices.
for(let i=0; i < arr.length; i++) {
if(arr[i].config !== '' || arr[i].payload !=='') {
isNext = false
break;
}else{
isNext = true;
}
}
use break to step out from loop.
Upvotes: 0
Reputation: 601
Break the loop instead of using return, the return keyword used to return values from methods
let arr = [
{
"config": "as",
"payload": ""
},
{
"config": "as",
"payload": "xc"
},
{
"config": "",
"payload": "xc"
},
{
"config": "",
"payload": ""
}
]
let isNext = true;
for(let i=0; i < arr.length; i++) {
if(arr[i].config !== '' || arr[i].payload !=='') {
isNext = false
break;
}else{
isNext = true;
}
}
console.log('next', isNext);
Upvotes: 1