简体   繁体   中英

How to remove 'undefined' on Object.keys for forEach

Hi Im using node Js and im having a problem on forEach on Object.keys , in the code below when i try to run it, there was an undefined value on the first value of output. For example lets say the value of input variable is:

input = [dog, cat, mouse, horse, pig];

Then when the program runs (refer the code below..) The value of val (with the forEach loop and Object.keys ) is

val = undefined dog plus the animal cat plus the animal mouse plus the animal horse plus the animal pig

I hope you guys understand my question, Thanks.

    var input = JSON.parse(JSON.stringify(req.body));
    var val;
    Object.keys(input).forEach(function(key) {
        if(key!='undefined')
        {
          val +=' '+key+' plus the animal';
        }
    });
    console.log(val);

change your var val; to var val = '' . When you write var val; , val is being assigned undefined onto which you are then concatenating your text. If you instead define val as a blank string, you won't get this problem. Also, as pointed out above, you don't need Object.keys since you are already working with an array

var input = JSON.parse(JSON.stringify(req.body));
var val = '';
input.forEach(function(key) {
  val +=' '+key+' plus the animal';
});
console.log(val);

Your solution seems fine. You just need to handle the first iteration and no need for Object.keys since input is an array.

var val;
input.forEach(function(key) {
    if(!val && key!='undefined')
        val = key + ' plus';
    else if(key!='undefined')
    {
      val +=' '+key+' plus the animal';
    }
});
console.log(val);

In JavaScript,if you don't assign a value to your variable when you declare it, it get undefined as defualt. So if you have something like this :

var drink; //The value is undefined now
drink +=' Milk';// now , this will be "undefined Milk"

in your code you have

var val;

value of val is undefined in this line

so you just need to set a value to val when you declare it, in your case it should be a string so :

var val="";

now you not gonna get "undefined" in your output anymore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM