Home > other >  add value to array where value in another array matches
add value to array where value in another array matches

Time:04-08

I'm trying to sort a table so that drag and drop sort order persists on refresh.

I have two arrays, one for contact details and another for sortOrder.

dragData array

[
    {
        "locationId": "1",
        "contactId": 6,
        "fields": [
            "john",
            "johnson",
            "dev",
            "123",
            "123",
            "[email protected]"
        ]
    },
    {
        "locationId": "1",
        "contactId": 5,
        "fields": [
            "test",
            "man",
            "dev",
            "12",
            "13",
            "[email protected]"
        ]
    }
]

and

orderArray

[
    {
        "id": 5,
        "sortOrder": 0
    },
    {
        "id": 6,
        "sortOrder": 1
    }
]

I'm trying to append the sort order onto an array thats mapped where contactId from first array is equal to id from second array. So the end product looks something like this.

end result

[
    {
        "contactId": 6,
        "firstName": "john"
        "lastName" : "johnson"
         ...
        "sortOrder": 1
    },
    {
        "contactId": 5,
        "firstName": "test"
        "lastName": "man"
        ...
        "sortOrder": 0
    }
]

So far I've tried a multitude of maps and filters. Currently at this point which obviously only returns true and false. What's the secret combination of maps needed to pull out the sortOrder for the contact via matching ids?

heres what ive got so far

const res = dragData.map((contact) => ({
        firstName: contact.fields[0],
        lastName: contact.fields[1],
        sortOrder: orderArray.map((item) => {
          return item.id === contact.contactId;
        }),
      }));

CodePudding user response:

const dragData = [
    {
        locationId: '1',
        contactId: 6,
        fields: ['john', 'johnson', 'dev', '123', '123', '[email protected]'],
    },
    {
        locationId: '1',
        contactId: 5,
        fields: ['test', 'man', 'dev', '12', '13', '[email protected]'],
    },
]

const orders = [
    {
        id: 5,
        sortOrder: 0,
    },
    {
        id: 6,
        sortOrder: 1,
    },
]

let orderTemp = {}

orders.forEach(item => {
    orderTemp[item.id] = { ...item }
})

const result = dragData.map(item => {
    return {
        ...item,
        sortOrder: orderTemp[item.contactId].sortOrder,
    }
})

console.log(result)

CodePudding user response:

const result = dragData.map((data) => {
   // check if the id in orderArray exist
   if (orderArray.some((sort) => sort.id === data.contactId)) {
      data.sortOrder = orderArray.find((sort) => sort.id === data.contactId).sortOrder;
      return data;
   } else {
      //if not just return the object without order
      return data;
   }
});

here is a simple code: codesandbox

  • Related