Filter Array Object by type and compare key value against Object

1508 views javascript
-3

I am stuck a bit here and looking for a possible simple solution to this.

I have an object like below

personObj  = { catname: "somecat" ,catname2: "somecat", dogname: "ruff", horsename: "sam"};

and then arrayObject like

personArr  = 
{ key: "a1", value: "catname" type: "cat" },
{ key: "a2", value: "catname2", type: "cat" },
{ key: "a3", value: "somedog" type: "dog" },
{ key: "a4", value: "horsename" type : "horse };

How can I create a function to filter all values by type in personArr and then check to see if any personObj Key matches a personArr value and if so return boolean?

filterAndCheckMatchedObj('cat', personObj){

//logic 

// Filtered by cat  2 matches (catname and catname2) 

return true 

}

//

I am using Angular 4 and Ionic

Does this even make sense? Any help would be appreciated.

answered question

not a valid JSON -> personArr

2 Answers

6

Try this,

var personObj  = { catname: "somecat" ,catname2: "somecat", dogname: "ruff", horsename: "sam"}

var personArr  = [{"key":"a1","value":"catname","type":"cat"},{"key":"a2","value":"catname2","type":"cat"},{"key":"a3","value":"somedog","type":"dog"},{"key":"a4","value":"horsename","type":"horse"}];

function find(type, personObj){
  return personArr.filter(item=>item.type === type).filter(item=>(item.value in personObj)).length !== 0
}

console.log(find('cat', personObj))

posted this
6

In order to filter parsonArr, you need it to be an array:

personArr  = [
    { key: "a1", value: "catname" type: "cat" },
    { key: "a2", value: "catname2", type: "cat" },
    { key: "a3", value: "somedog" type: "dog" },
    { key: "a4", value: "horsename" type : "horse }
];

In declaration of a function, you don't pass parameter, just declare them:

filterAndCheckMatchedObj(animalType, personObj) {
    const filteredParsonArr = personArr.filter(person => person.type === animalType);
}

Now you need any relation between personArr to personObj. I suggest you to change personObj:

personObj  = { cat: ["somecat", "somecat2"], dog: ["ruff"], horse: ["sam"]};

Now, if you have type="cat", you can use it by: personObj[type].

To sum up:

const personArr  = [
    { key: "a1", value: "catname" type: "cat" },
    { key: "a2", value: "catname2", type: "cat" },
    { key: "a3", value: "somedog" type: "dog" },
    { key: "a4", value: "horsename" type : "horse }
];
const personObj  = { cat: ["somecat", "somecat2"], dog: ["ruff"], horse: ["sam"]};
function filterAndCheckMatchedObj(animalType, personObj) {
    const filterByType = personArr.filter(person => 
        person.type === animalType &&
        personObj[person.type]);

    return filteredPersonArr.length > 0;   
}

console.log(filterAndCheckMatchedObj('cat', personObj')); // prints true

posted this

Have an answer?

JD

Please login first before posting an answer.