[英]Filter an array of objects and get its property by using an array of values
大家好,這似乎是重復的,因為我已經質疑了這個問題,但已經回答了,但是這次有所不同。
上一個問題: 我已經回答過的上一個問題
所以這是我的問題,我有一組對象(人),其屬性分別為“名稱”和“角色”。 我有另一個數組稱為“工作”。 如果我使用代碼示例,那就更好了。
var jobs = ['engineer','scientist','developer'];
var people = [ {name:'John', role:'engineer'},
{name:'Jane', role:'scientist'},
{name:'Jonathan', role:'developer'},
{name:'Jane', role:'engineer'} ];
如您所見,可以看到具有相同屬性“名稱”的對象,但角色不同。 我想根據其角色使用“職位”數組將它們提取到新數組中。
輸出示例如下:
var peopleWithJobs = [
{name:'John', jobs:['engineer'] }
{name:'Jane', jobs:['scientist', 'engineer'] },
{name:'Jonathan', jobs:['developer'] }
]
如果在'people'數組上重復'name'屬性值,則只需獲得角色並將其推入/追加到新數組'peopleWithJobs'的jobs屬性中即可。
我一直在使用map和filter更高階的函數,但是對於javascript來說還很陌生,只是無法理解這個邏輯。
var jobs = ['engineer','scientist','developer']; var people = [ {name:'John', role:'engineer'}, {name:'Jane', role:'scientist'}, {name:'Jonathan', role:'developer'}, {name:'Jane', role:'engineer'} ]; var peopleWithJobs = []; for(var x=0;x<people.length;x++) { if(jobs.indexOf(people[x].role) != -1) { var uniqueNames = peopleWithJobs.map(function(val) { return val.name; }); if(uniqueNames.indexOf(people[x].name) == -1) peopleWithJobs.push({name: people[x].name, jobs: [people[x].role]}); else { peopleWithJobs[uniqueNames.indexOf(people[x].name)].jobs.push(people[x].role); } } } console.log(peopleWithJobs);
當您第一次對數組進行排序時,構造新數組非常簡單。 在檢查名稱是否與以前的名稱相同之后,您可以將項目逐個推送到新數組中,在這種情況下,您只能將角色推送到先前的人員。
var people = [ {name:'John', role:'engineer'}, {name:'Jane', role:'scientist'}, {name:'Jonathan', role:'developer'}, {name:'Jane', role:'engineer'} ]; function reconstruct(arr) { // Sort var arr = arr.slice().sort(function(a,b) { var x = a.name.toLowerCase(); var y = b.name.toLowerCase(); return x < y ? -1 : x > y ? 1 : 0; }); // Construct new array var newArr = []; for (i=0; i<arr.length; i++) { if (arr[i-1] && (arr[i].name == arr[i-1].name)) { newArr[newArr.length-1].role.push(arr[i].role) } else { newArr.push({name: arr[i].name, role: [arr[i].role]}); } } return newArr; } console.log(reconstruct(people));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.