简体   繁体   中英

Get rid of `undefined` in a array of objects

I have this function that receives params as an argument:

export const addCalculations = (params) => {
  console.log(params);
};

Then I want to access to the id value but when I do params[0].id it throws an error (Cannot read property id of undefined). When I see the console, that function is being called multiple times and it returns undefined sometimes. How can I get rid of those undefined and only get the last array?

在此处输入图片说明

params[0] itself is undefined so before going to call params[0].id you should make a check

if (params[0]) {
   id = params[0].id;
   ...
}

If you want to filter the array of params, you can use filter function

filterd = params.filter( x => {

  if (x) {
   return true;
  } 

  return false;

})

//continue with filtered 
...

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