Doug Fir
Doug Fir

Reputation: 21212

Check which of an array value is also an object property

I have a object 'ecom' which will have a property that is one of ['detail','add','remove','checkout','purchase']

I want to know which of the 5 potential properties the object has.

What is the shortest, cleanest way to get that?

Upvotes: 1

Views: 46

Answers (1)

Maheer Ali
Maheer Ali

Reputation: 36564

You can use filter() and hasOwnProperty()

let arr = ['detail','add','remove','checkout','purchase'];
let obj = {detail:'val',add:0,purchase:33}


let res = arr.filter(x => obj.hasOwnProperty(x));
console.log(res)

Without arrow function

let arr = ['detail','add','remove','checkout','purchase'];
let obj = {detail:'val',add:0,purchase:33}


let res = arr.filter(function(x){
    return obj.hasOwnProperty(x)     
}) 
console.log(res)

Upvotes: 4

Related Questions