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:
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.
To get first element from array, use var first = array[0]; To get Name from it, use first.Name .
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.
The shift() method removes the first element from an array and returns that removed element. This method changes the length of the 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.
Array method, you can use Array.prototype.shift()
.
let selectedShop = initialResultsState.get('products')
.filter(product => product.shop.selected)
.shift();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With