Search code examples
javascriptecmascript-6filterecmascript-2016

How to filter array of objects and only return one result without the array brackets


I may not have had enough coffee on this lovely monday morning but there's something simple I'd like to do that is not coming to me.

I am filtering on an array of objects for an id:

const skuVariant = skuOptions.filter(sku => sku.itemNumber === variantItemNumber);

This returns an array that is of length 1 if there is a match. The following line I have:

const skuVariantValueMap = skuVariant && skuVariant[0].varianceValueMap;

I would like to not have to check the for the first element of the array and instead only return the object from the call to filter and not the object inside an array.

To be extra clear skuVariant returns this: [{id: 1234}]

I would like it to return this: { id: 1234 }

This is possible using lodash utils but that's overkill. I am looking for something vanilla.

Is there an ES7, ES6 / super clean way of achieving this?

Thanks in advance.


Solution

  • Use Array.prototype.find instead of filter. It returns the value of the first element in the array that satisfies the provided testing function.