JavaScript How to filter array of objects by dynamic key?
I have an array which contains objects with dynamic keys, my aim is to find if this array contains or not specific key, How can this be achieved?
let arr = [
{item1: { key: 'sdfd', value:'sdfd' }},
{item2: { key: 'sdfd', value:'sdfd' }},
{item3: { key: 'sdfd', value:'sdfd' }}
]
let target = 'item1'
//result array
let arr = [
{item1: { key: 'sdfd', value:'sdfd' }},
]
Use Array#filter()
and the in
operator
let arr = [
{item1: { key: 'sdfd', value:'sdfd' }},
{item2: { key: 'sdfd', value:'sdfd' }},
{item3: { key: 'sdfd', value:'sdfd' }}
]
let target = 'item1'
console.log(
arr.filter(i => target in i)
)
Based on your title, I assume you want to try using array.filter
, so follow up your attempt of using array.filter
, this is an opion:
let arr = [
{item1: { key: 'sdfd', value:'sdfd' }},
{item2: { key: 'sdfd', value:'sdfd' }},
{item3: { key: 'sdfd', value:'sdfd' }}
]
let target = 'item1'
let newarr= arr.filter(each=>Object.keys(each).toString() ==target)
console.log(newarr)