[英]Alternatives to nested for loops in Javascript
我需要取數組一中的一個元素,並將其與數組二的所有其他元素進行比較,以查看是否匹配。 我需要對數組一中的每個元素執行此操作。
for ( let i = 0, j = userArray.length; i < j; i++) {
for ( let c = 0, d = userArray.length; c < d; c++) {
object = {
id: userArray[i].account,
name: userArray[i].name,
title: "",
rating: ""
}
if ( userArray[i].account === accountArray[c].id) {
object.title = accountArray[c].title.title
}
if (object.title !== ""){
objectArray.push(object)
}
}
}
有沒有更有效的方法來解決這個問題。
期望的結果是將 accountArray 的每個元素與 userArray 的每個單獨元素進行比較以搜索匹配項
您可以使用數組reduce()
方法來過濾您的userArray
並將其映射到具有組合結果的新數組中。
這是一個示例(帶有存根數據):
const userArray = [ { account: 1, name: 'user 1' }, { account: 2, name: 'user 2' }, { account: 3, name: 'user 3' }, { account: 4, name: 'user 4' }, { account: 5, name: 'user 5' } ]; const accountArray = [ { id: 1, name: 'account 1', title: 'account 1 title' }, { id: 3, name: 'account 3', title: 'account 3 title' }, { id: 5, name: 'account 5', title: 'account 5 title' } ]; const mergedList = userArray.reduce((acc, u) => { const account = accountArray.find(a => a.id === u.account); if (account) { acc.push({ id: u.account, name: u.name, title: account.title, rating: '' }) } return acc; }, []); console.log(mergedList);
您可以使用 Array.find 或 Array.filter
Array.find - 返回第一個匹配元素
array.find(item => item.id === 1)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
Array.filter - 返回所有匹配元素的數組
array.filter(item => item.id === 1)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
希望能幫助到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.