使用es6数组方法从数组中提取第一个对象

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总是返回一个新数组。

Dan*_*ski 6

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();
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

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


但是您可能会看到另一种方法,答案是(Mikael Lennholm的答案)Array.prototype.find()。这样可以提高性能。

  • pop()返回(并删除)最后一项,而不是第一项。“ shift”获取(并删除)第一个。 (2认同)

Len*_*olm 5

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.