I currently working on filtering an array of object.
The array of objects goes like this
var arrayObj = [
{
"Fajr": "04:29 (WIB)",
"Dhuhr": "11:43 (WIB)",
"Asr": "14:48 (WIB)",
"Maghrib": "17:48 (WIB)",
"Isha": "18:53 (WIB)"
},
{
"Fajr": "04:29 (WIB)",
"Dhuhr": "11:43 (WIB)",
"Asr": "14:47 (WIB)",
"Maghrib": "17:48 (WIB)",
"Isha": "18:53 (WIB)"
}
]
And I have the Array that can change but the range is only 0 to 4. the example is like this
var arrayFind = [3, 0, 4]
What I want to achieve is the arrayObj
will filter based on arrayFind
, example the output is like this
var arrayObj = [
{
"Fajr": "04:29 (WIB)",
"Maghrib": "17:48 (WIB)",
"Isha": "18:53 (WIB)"
},
{
"Fajr": "04:29 (WIB)",
"Maghrib": "17:48 (WIB)",
"Isha": "18:53 (WIB)"
}
]
How do I achieve that ? I tried to use map
and _.pickBy
but still stuck.
Thank you so much
CodePudding user response:
We can use Object.keys()
to get all the keys and then using map()
to do it
var arrayObj = [
{
"Fajr": "04:29 (WIB)",
"Dhuhr": "11:43 (WIB)",
"Asr": "14:48 (WIB)",
"Maghrib": "17:48 (WIB)",
"Isha": "18:53 (WIB)"
},
{
"Fajr": "04:29 (WIB)",
"Dhuhr": "11:43 (WIB)",
"Asr": "14:47 (WIB)",
"Maghrib": "17:48 (WIB)",
"Isha": "18:53 (WIB)"
}
]
var arrayFind = [3, 0, 4]
let result = arrayObj.map(e => {
let keys = Object.keys(e)
let obj = {}
arrayFind.forEach(a => {
obj[keys[a]] = e[keys[a]]
})
return obj
})
console.log(result)