spotlight world
spotlight world

Reputation: 3

filter array of objects by value in javascript

I'm trying to filter the object based on the array values given below. I know how to filter object through the key but in this scenario I need to filter it by values.

This is my code:

let _ = [{
        "form_id": "659d796d-aa78-4e74-af68-5ef037bb215b",
        "form_name": "Investigation Forms",
        "form_type": null,
        "created_at": "",
        "updated_at": ""
    },
    {
        "form_id": "9991f556-fc7f-4400-a491-062b12a0bb03",
        "form_name": "Other Investigation Forms",
        "form_type": {
            "form_type_name": "Assessment",
            "form_type_id": "5f4419c1-9351-4338-b894-84a000328cc4"
        },
        "created_at": "",
        "updated_at": ""
    },
    {
        "form_id": "9991f556-fc7f-4400-a491-062b12a0bb03",
        "form_name": "Other/General Investigation Forms",
        "form_type": {
            "form_type_name": "Report",
            "form_type_id": "594ba131-b110-4ec5-855a-9de8440fbc7b"
        },
        "created_at": "",
        "updated_at": ""
    }
]

//-------------------------------------------------------------------------------------------------

const values = [0, "5f4419c1-9351-4338-b894-84a000328cc4", "594ba131-b110-4ec5-855a-9de8440fbc7b"]

plz ignore my below code it is work attempt . 

const output = _.map(item =>
    values.reduce((val, key) => ({
        ...val,
        [key]: item[key]
    }), {})
);
console.log(output);


my expected output :
const values = ["5f4419c1-9351-4338-b894-84a000328cc4"]

output = [{
 "form_id": "9991f556-fc7f-4400-a491-062b12a0bb03",
        "form_name": "Other Investigation Forms",
        "form_type": {
            "form_type_name": "Assessment",
            "form_type_id": "5f4419c1-9351-4338-b894-84a000328cc4"
        },
        "created_at": "",
        "updated_at": ""
}]

The form_type has form_type_id, this is the value I need to be filter by.

Upvotes: 0

Views: 89

Answers (1)

Zoltan Magyar
Zoltan Magyar

Reputation: 873

If I understood your question correctly then you need

_.filter((item) => values.includes(item.form_type?.form_type_id));

or if optional chaining is not available (as correctly pointed out by Obed Marquez Parlapiano)

_.filter((item) => values.includes(item.form_type && item.form_type.form_type_id));

See test at https://jsfiddle.net/snLqx4g9/

Upvotes: 1

Related Questions