1
var imageArr = [];
if(req.body.photo1){
  imageArr.push(req.body.photo1);
}
if(req.body.photo2){
  imageArr.push(req.body.photo2);
}
if(req.body.photo3){
  imageArr.push(req.body.photo3);
}
if(req.body.photo4){
  imageArr.push(req.body.photo4);
}

How to improve above code? I wrote a loop but I got undefined1,undefined2,undefined3,undefined4 value in my array.

for(var i = 1; i<=4;i++){
if(req.body.photo+''+i){
imageArr.push(req.body.photo+''+i);
}
}

1 Answer 1

3

since "photo" + i is a variable key, you need to access it as req.body [ "photo" + 1 ]

for(var i = 1; i<=4;i++)
{
  var value = req.body[ "photo"+ i];
  if( value ) 
  {
    imageArr.push(value);
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

is assigning it to a value variable compulsory?

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.