sujon
sujon

Reputation: 367

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"]

Upvotes: 1

Views: 50

Answers (2)

mplungjan
mplungjan

Reputation: 177692

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)

Upvotes: 2

Radu Diță
Radu Diță

Reputation: 14171

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

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

Upvotes: 1

Related Questions