use*_*079 6 javascript arrays ecmascript-6
我有以下代码来获取一个对象的数组:
let selectedShop = initialResultsState.get('products')
.filter(product => product.shop.selected)
Run Code Online (Sandbox Code Playgroud)
console.log(selectedShop)
结果:
我是否可以通过在另一操作中将另一个es6数组方法插入字符串的末尾filter而不是这样做从数组中提取对象let newVariable = selesctedShop[0]?
我试图把它串起来:
.map(x => {return { shop: x.shop, products: x.products }})
Run Code Online (Sandbox Code Playgroud)
但它仍然是一个对象的数组,因为map总是返回一个新数组。
Array method, you can use Array.prototype.shift().
let selectedShop = initialResultsState.get('products')
.filter(product => product.shop.selected)
.shift();
Run Code Online (Sandbox Code Playgroud)
You can do this, by destructuring assignment. In your case:
let [selectedShop] = initialResultsState.get('products')
.filter(product => product.shop.selected);
Run Code Online (Sandbox Code Playgroud)
This is available in ES6, supported in major browsers without transpiling.
但是您可能会看到另一种方法,答案是(Mikael Lennholm的答案)Array.prototype.find()。这样可以提高性能。
How about using the find() method instead of filter()? find() always return a single item, not wrapped in an array, unless it doesn't find any item, in which case it returns undefined
let selectedShop = initialResultsState.get('products')
.find(product => product.shop.selected)
Run Code Online (Sandbox Code Playgroud)
It's also a lot more efficient since it actually stops iterating over the array as soon as it has found an item. filter() will always iterate over the entire array which is a waste if you're only interested in the first relevant item anyway.
| 归档时间: |
|
| 查看次数: |
2274 次 |
| 最近记录: |