我有兩個物件陣列:
let employees = [
{ name: 'Jason', job_id: '101' },
{ name: 'Sarah', job_id: '102' },
{ name: 'Jack', job_id: '102' }
]
let jobs = [
{ job_id: '101', position: 'Designer' },
{ job_id: '102', position: 'Developer' }
]
我是否可以使用 vanilla javascript 將這些陣列合并為一個,如下所示:
let employees = [
{ name: 'Jason', job_id: [job_id: '101', position: 'Designer'] },
{ name: 'Sarah', job_id: [job_id: '102', position: 'Developer'] },
{ name: 'Jack', job_id: [job_id: '102', position: 'Developer'] }
]
以下是我現在所擁有的。它確實給了我正確的結果,但是如果可能的話,我寧愿不使用嵌套回圈。
employees.forEach(employee => {
for (let index = 0; index < jobs.length; index ) {
if (employee.job_id == jobs[index].job_id) {
employee.job_id= jobs[index];
}
}
})
uj5u.com熱心網友回復:
任務不是很復雜,所以我將嘗試通過現場演示做出簡單的回答。
這里的想法是遍歷employees
陣列,然后構造一個具有所需結構的物件,然后將其推入最終陣列。
最終陣列上的每個物件都將具有以下屬性:
name
:等于employees
陣列上的名稱(每次迭代)job
:為了讓事情更清楚,我會使用job
而不是job_id
(你在你想要的結果中使用它)。job
是一個物件, 包含id
:job_id
來自employees
陣列position
jobs
:陣列中的相應位置。
為了得到上述結果,我們將使用reduce
構建最終陣列的方法。
另一個任務是根據employees 表position
從jobs
陣列中獲取相應的 ,。job_id
為此,我們將使用find
回傳在jobs
陣列中找到的第一個匹配項的方法。
話雖如此,讓我們來一個現場演示(演示有一些有用的評論):
const employees = [{
name: 'Jason',
job_id: '101'
},
{
name: 'Sarah',
job_id: '102'
},
{
name: 'Jack',
job_id: '102'
}
],
jobs = [{
job_id: '101',
position: 'Designer'
},
{
job_id: '102',
position: 'Developer'
}
],
/**
* "res" is the resulting array after performing the needed operations
* "reduce" method loops through the "employees" array and populates the "res" array along the way
*/
res = employees.reduce((a, c) => {
/**
* a: the accumulator, it holds the last value from the previous iteration. Initially it equals to an empty array "[]" (see 3rd argument passed to the "reduce" method)
* c: is the current element from the "employees" array on each iteration
*/
/** adds an object that follows the intended structure to the final array */
a.push({
name: c.name,
job: {
id: c.job_id,
/**
* find the respective "position" based on the "job_id" of the current element of element of the "employees" arrray
* el: holds the element from "jobs" array on each iteration of the "find" method
* the condition is once we find an elemnt having "job_id" equals to the current element (i mean "c" parameter) "job_id" then return that object's "position" attribute
* once we found the "position" we simply save it on the object we're constructing
*/
position: jobs.find(el => el.job_id == c.job_id).position
}
});
/** return the array so that the next iteration of "reduce" can do its work */
return a;
}, []);
/** print the result */
console.log(res);
上面的演示絕對不是完成事情的唯一方法,當然有一些奇特的
ES6
方法可以做到這一點,尤其是在構造物件時。為了簡單起見,我不會使用那些花哨/復雜的技巧來使事情盡可能簡單易懂。
reduce
在 MDN 上了解有關該方法的更多資訊。
find
在 MDN 上了解有關該方法的更多資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/508338.html
標籤:javascript 数组