Friday 23 November 2018

Finding the index of an array of objects by one of the object's properties

I've been doing a shed load of work with lodash of late and, seeing as I've not posted in an age, I thought I'd illustrate an issue I was working on today.

I needed to pass an element of an array to a Vue component but needed a specific one identified by another object. We use lodash so thought I'd make use of findIndex and isEqual and came up with this:

const obj = {
    id: 1,
    name: "fred"
};

const arr = [{
    a: "B",
    s: {
        id: 1,
        name: "fred"
    }
}, {
    a: "A",
    s: {
        id: 2,
        name: "fred"
    }
}];

alert(arr[_.findIndex(arr, (a) => _.isEqual(a.s, obj))].a);

Heat eh?