Search code examples
javascriptobjectfilter

How to get any id(value) from object as per value selection in JavaScript


I have an object having key value pair i.e. id and value as attached below.

var dataObject = [
    {
        "value": "A",
        "id": 1,
    },
    {
        "value": "B",
        "id": 2,
    },
    {
        "value": "C",
        "id": 3,
    },
    {
        "value": "D",
        "id": 4,
    },
    {
        "value": "E",
        "id": 5,
    }
]

I am selecting value from multiselector from front end, for example I am selecting B and C

var selectedData = ['B', 'C']

I am expecting below object to send as a payload from dataObject.

"selection": [
    {
      "siteId": 2
    },
    {
      "siteId": 3
    }
  ],

I have tried with filter() and map() like this

var result = dataObject.filter(item => item.value === 'B').map(item => item.id);

But not get proper result

Thanks in advance.


Solution

  • You can use the includes Array method.

    var result = dataObject.filter(item => selectedData.includes(item.value) ).map(item => ({siteId:item.id}));
    

    BTW, It will only work if the order of selectedData is the same as dataObject.