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)
JavaScript has built-in functions that return the object's keys for you:
var x = {
name : "Romulo",
age : 17
}
console.log(Object.keys(x))
Output:
["name","age"]
This returns an array, you just need check if your key is in it.
You can use Array.filter method and Object.hasOwn method for this, please never use the in
operator it has some precedence issues.
const arr = [ {item1: { key: 'sdfd', value:'sdfd' }}, {item2: { key: 'sdfd', value:'sdfd' }}, {item3: { key: 'sdfd', value:'sdfd' }} ] function filterByKey(list, target) { return list.filter( item => Object.hasOwn(item, target) ); } const target = "item1"; console.log( filterByKey(arr, target) );
[
{item1: { key: 'sdfd', value:'sdfd' }},
{item2: { key: 'sdfd', value:'sdfd' }},
{item3: { key: 'sdfd', value:'sdfd' }}
]
Want the data from target
, when target is item1
:
[
{item1: { key: 'sdfd', value:'sdfd' }}
]
let arr = [ {item1: { key: 'sdfd', value:'sdfd' }}, {item2: { key: 'sdfd', value:'sdfd' }}, {item3: { key: 'sdfd', value:'sdfd' }} ] let target = 'item1' // result array let want = [ {item1: { key: 'sdfd', value:'sdfd' }}, ]
let arr = [ {item1: { key: 'sdfd', value:'sdfd' }}, {item2: { key: 'sdfd', value:'sdfd' }}, {item3: { key: 'sdfd', value:'sdfd' }} ] let target = 'item1' // result array let want = [ {item1: { key: 'sdfd', value:'sdfd' }}, ] let answer = arr.filter(object => object[target]) console.log('answer:', answer)
Does this answer your question? or if not comment to tell what went wrong.
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.