Filtering undefined from array of objects in Javascript

假如想象 提交于 2020-05-16 05:58:44

问题


I am having trouble sorting out the undefined from the array of objects that was crated from local storage. Lets assume that this array of of objects is localStorage:

var arrObject = [{date: undefined, bus_name: Thomas #1};...] Assume this has 2 dates that had undefined.

I want to be able to filter out the date that has undefined and the bus_name that is within the date so for example, if I used filter for an array of objects before sorting them, then {date: undefined, bus_name: Thomas #1} will not be included in the array that will be sorted.

How would I accomplish this?

Thanks!

UPDATE: 3/5/20

How would I accomplish this if I have more than 2 columns, lets say I have at least 5, I want to filter and sort date as well as only output date and bus_name

var arrObject = [{date: undefined, bus_name: Thomas #1, bus_driver: Thomas, time_start: 9AM, time_end: 5PM};...]

Output: {date: ..., bus_name:...}; {...}


回答1:


i think you should provide filter with condation field (one is date, another is bus_name )

anyway i want clear it out that :--

 i) arrObject.filter(e => e.date)  // with this all {date: undefined } contain object will be filter and get data which have actual date value 

 ii) arrObject.filter(e => e.date === undefined) // give filter result with all date undefined  
iii) arrObject.filter(e => e.date === undefined && e.bus_name ) or arrObject.filter(e => e.date && e.bus_name)

which one of the result you are expecting




回答2:


You can use this method:

const arrObject = [
{date: undefined, bus_name: 'Thomas #1'},
{date: '2012-02-11', bus_name: 'Thomas #2'},
{date: '2012-02-02', bus_name: 'Thomas #3'},
{date: '2012-02-04', bus_name: 'Thomas #4'},
{date: undefined, bus_name: 'Thomas #5'},
{date: '2012-02-03', bus_name: 'Thomas #6'},
{date: '2012-02-03', bus_name: 'Thomas #7'},
]
function formatTheDate (str){
  //your format here
  let FormatedDate = "new Date format" + str 
  return FormatedDate
}

let newArray = arrObject.filter( obj => {
  obj.formattedDate = formatTheDate(obj.date)
  //behave same as obj.date != undefined
  return obj.date
}).sort((a,b)=>{
  return Date.parse(a.date) - Date.parse(b.date)
})

console.log(newArray);

EDIT: updated the answer to return sorted result based on the date;



来源:https://stackoverflow.com/questions/60514157/filtering-undefined-from-array-of-objects-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!