Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract first object from array with es6 array methods

I have this code to get an array of one object:

let selectedShop = initialResultsState.get('products')
        .filter(product => product.shop.selected)

console.log(selectedShop)

result:

enter image description here

Can I extract the object from the array in the same operation by stringing another es6 array method to the end of filter, rather than doing let newVariable = selesctedShop[0]?

I tried to string this to it:

.map(x => {return { shop: x.shop, products: x.products }})

but it is still an array of one object because map always returns a new array.

like image 453
user2602079 Avatar asked Jun 22 '17 08:06

user2602079


People also ask

How do I find the first object of an array of objects?

To get first element from array, use var first = array[0]; To get Name from it, use first.Name .

How would you get the 1st element in an array in JavaScript?

Javascript array is a variable that holds multiple values at a time. The first and last elements are accessed using an index and the first value is accessed using index 0 and the last element can be accessed through length property which has one more value than the highest array index.

How do you take the first element of an array?

The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.

How do I return the first index of an array?

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.


1 Answers

Two basic ways:

First way is shift'ing:

Array method, you can use Array.prototype.shift().

let selectedShop = initialResultsState.get('products')
    .filter(product => product.shop.selected)
    .shift();

Second way is an assignment:

You can do this, by destructuring assignment. In your case:

let [selectedShop] = initialResultsState.get('products')
    .filter(product => product.shop.selected);

This is available in ES6, supported in major browsers without transpiling.


But you could see another approach, in answers (Mikael Lennholm's answer) is Array.prototype.find(). This can be more performance-effective.

like image 57
Daniel Mizerski Avatar answered Sep 19 '22 02:09

Daniel Mizerski