简体   繁体   中英

Why am I getting undefined entries in the following javascript code

So below is my javascript code

 const rData = [[{"prop11": 10}, {"prop2": 12}]]; const tData = []; const tddData = []; for(const item of rData[0]){ tData.push(Object.keys(item).toString()); console.log('trData...', tData); tData.map(y => { tddData.push(item[y]); console.log('tdDta....', tddData); }); } 

Following is the output of the console.logs

trData... Array [ "prop11" ] 
tdDta.... Array [ 10 ] 
trData... Array [ "prop11", "prop2" ] 
tdDta.... Array [ 10, undefined ] 
tdDta.... Array [ 10, undefined, 12 ]

I can't seem to understand where those undefined values are coming from. Please help.

On the second iteration of the for loop, item is {"prop2": 12} and tData is ["prop11", "prop2"] . When you call tData.map() , you do:

tddData.push(item["prop11"]);
tddData.push(item["prop2"]);

Since there is no item["prop11"] , you get undefined for that one.

tData contains the keys from all the previous objects in the array, so you'll get undefined whenever a later object doesn't have those previous keys.

Also, if any of the object has multiple properties, Object.keys(item).toString() will be a comma-separated list of keys. For instance, if you have

{"key1": 1, "key2": 3}

you'll push "key1,key2" onto tdData . When you try to use this in item[y] , you'll get undefined .

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