私は以下のようなオブジェクトの配列を持っています
readonly allItems = [
{
id: 0,
title: "Item 0",
belongsTo: 'admin'
},
{
id: 1,
title: "Item 1",
belongsTo: 'user'
},
{
id: 2,
title: "Item 2",
belongsTo: 'all'
},
{
id: 3,
title: "Item 3",
belongsTo: 'user'
},
{
id: 4,
title: "Item 4",
belongsTo: 'all'
}
];
そして、私は以下のような数字の配列を持っています
let selItems = [0,2,4];
私がやろうとしているのは、allItems
配列に基づいて配列をフィルタリングすることです。selItems
そのために、次のコードを記述しましたが、これは明らかに間違っています。
for(let i=0; i< this.allItems.length; i++){
if(selItems.includes(this.allItems[i].id)){
tempMenu.push(this.allItems[i]);
}
console.log(tempMenu);
}
以下を出力として取得しています
[{
id: 0,
title: "Item 0",
belongsTo: 'admin'
}]
私が期待している結果は次のようになります。
[
{
id: 0,
title: "Item 0",
belongsTo: 'admin'
},
{
id: 2,
title: "Item 2",
belongsTo: 'all'
},
{
id: 4,
title: "Item 4",
belongsTo: 'all'
}
]
誰かが私にこれを行う正しい方法を教えてもらえますか?ありがとう!
.map
代わりに次のものを使用できます。
const allItems = [{
id: 0,
title: "Item 0",
belongsTo: 'admin'
},
{
id: 1,
title: "Item 1",
belongsTo: 'user'
},
{
id: 2,
title: "Item 2",
belongsTo: 'all'
},
{
id: 3,
title: "Item 3",
belongsTo: 'user'
},
{
id: 4,
title: "Item 4",
belongsTo: 'all'
}
];
const selItems = [0, 2, 4];
const output = selItems.map(num => allItems.find(({ id }) => id === num));
console.log(output);
計算の複雑さをのO(N)
代わりに減らすためにO(N^2)
、id
最初にインデックスが付けられたオブジェクトに変換できます。
const allItems = [{
id: 0,
title: "Item 0",
belongsTo: 'admin'
},
{
id: 1,
title: "Item 1",
belongsTo: 'user'
},
{
id: 2,
title: "Item 2",
belongsTo: 'all'
},
{
id: 3,
title: "Item 3",
belongsTo: 'user'
},
{
id: 4,
title: "Item 4",
belongsTo: 'all'
}
];
const selItems = [0, 2, 4];
const allItemsById = allItems.reduce((a, item) => {
a[item.id] = item;
return a;
}, {});
const output = selItems.map(num => allItemsById[num]);
console.log(output);
またはとfilter
:
const allItems = [{
id: 0,
title: "Item 0",
belongsTo: 'admin'
},
{
id: 1,
title: "Item 1",
belongsTo: 'user'
},
{
id: 2,
title: "Item 2",
belongsTo: 'all'
},
{
id: 3,
title: "Item 3",
belongsTo: 'user'
},
{
id: 4,
title: "Item 4",
belongsTo: 'all'
}
];
const selItemsSet = new Set([0, 2, 4]);
const output = allItems.filter(({ id }) => selItemsSet.has(id));
console.log(output);
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加