简体   繁体   中英

How to filter array in javascript

Here is my array of two values.

let dataList = ["x","y","z","a","b"]
let data2= {
  x:{hide:true},
  y:{hide:true},
  z:{},
  a:{}
}

here is my trying code:

let filters = dataList.filter(item=>Object.keys(data2).includes(item))

I want to filter dataList based data2 - hide:true. For example, if values object property hide:true inside data2, key will be removed.

expected output:

["z","a"]

I believe it is a simple as this

 let dataList = ["x","y","z","a","b"] let data2= { x:{hide:true}, y:{hide:true}, z:{}, a:{} } let filters = dataList.filter(item=> data2[item] &&.data2[item].hide) console.log(filters)

You can check if the key exists on data2 and check for hide to be true

dataList.filter(item => data2[item] &&.data2[item].hide )

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