[英]Efficient Way of Filtering Array and Mapping in ES6
我想獲得僅具有“現有” status
的數組,並且不在 newArray 中添加狀態。 最有效的方法是什么?
const products = [
{
"id": "111",
"name": "grapes",
"status": "Linked",
},
{
"id": "222",
"name": "banana",
"status": "Existing",
},
{
"id": "333",
"name": "mango",
"status": "Existing",
},
{
"id": "444",
"name": "salad",
"status": "Linked",
},
{
"id": "555",
"name": "juice",
"status": "Existing",
}
]
const newArray =
products?.map(({ name = '', id = '' }) => ({
name,
id,
}))
我認為問題是你試圖在一個數組 function 中同時執行這兩項操作。我會使用 filter 按status === "Existing"
filter
它,然后map
它,刪除status
屬性。
const products = [{ "id": "111", "name": "grapes", "status": "Linked", }, { "id": "222", "name": "banana", "status": "Existing", }, { "id": "333", "name": "mango", "status": "Existing", }, { "id": "444", "name": "salad", "status": "Linked", }, { "id": "555", "name": "juice", "status": "Existing", } ] const newArray = products.filter((elem) => elem.status === "Existing").map(({ id, name, status }) => ({ id, name })) console.log(newArray);
就代碼行而言,最有效的可能只是filter()
后跟map()
操作:
const result = products.filter(({status}) => status === 'Existing')
.map(({id, name}) => ({id, name}));
完整片段:
const products = [{ "id": "111", "name": "grapes", "status": "Linked", }, { "id": "222", "name": "banana", "status": "Existing", }, { "id": "333", "name": "mango", "status": "Existing", }, { "id": "444", "name": "salad", "status": "Linked", }, { "id": "555", "name": "juice", "status": "Existing", }]; const result = products.filter(({status}) => status === 'Existing').map(({id, name}) => ({id, name})); console.log(result);
由於這需要兩次迭代,因此在性能方面最有效的可能是將匹配值推入結果數組的顯式for
循環。
如果你想在一次迭代中完成所有事情但仍然保持一種功能性方法,你可以用一個reduce()
操作完成所有事情:
const products = [{ "id": "111", "name": "grapes", "status": "Linked", }, { "id": "222", "name": "banana", "status": "Existing", }, { "id": "333", "name": "mango", "status": "Existing", }, { "id": "444", "name": "salad", "status": "Linked", }, { "id": "555", "name": "juice", "status": "Existing", }]; const result = products.reduce((a, {id, name, status}) => { if (status === 'Existing') a.push({id, name}); return a; }, []); console.log(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.