2017-06-22 58 views
0

嘿傢伙這必須看起來重複,因爲我已經質疑這已被回答,但這次它有點不同。過濾對象的數組,並通過使用值的數組來獲得它的屬性

前面的問題: My previous question which is already been answered

所以這是我的問題,我有對象(人)財產被稱爲「名」的數組,「角色」。我有另一個名爲'Jobs'的數組。如果我使用代碼示例,效果會更好。

var jobs = ['engineer','scientist','developer']; 
var people = [ {name:'John', role:'engineer'}, 
       {name:'Jane', role:'scientist'}, 
       {name:'Jonathan', role:'developer'}, 
       {name:'Jane', role:'engineer'} ]; 

正如你可以看到具有相同屬性'名稱'的對象可以看到,但具有不同的作用。我想根據他們的角色使用'jobs'數組將他們提取到一個新數組中。

例輸出將是:重複「人」的陣列上

var peopleWithJobs = [ 
         {name:'John', jobs:['engineer'] } 
         {name:'Jane', jobs:['scientist', 'engineer'] }, 
         {name:'Jonathan', jobs:['developer'] } 
        ] 

如果「名」的屬性值是拿到作用,推動/追加到作業的新陣列「peopleWithJobs」的屬性。

我一直在使用地圖和篩選更高階的功能,但即時通訊相當新的JavaScript,只是不能把我的頭圍繞這個邏輯。

+1

我覺得做一個新的對象,使用人的名字爲重點,以創建你的工作會更容易 –

回答

0

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);

+0

從沒想過的indexOf方法,謝謝老兄我學到了一些東西,所以如果' - 1'它只是表示它不存在於陣列上嗎? –

+0

是的。如果indexOf返回-1,那麼它不存在於數組中。這是一個非常有用的功能。 –

0

當你第一次排序的數組,構建新的數組是非常簡單的。在檢查名稱是否與以前的名稱相同之後,您可以逐個將這些項目推送到新陣列,在這種情況下,您只會將角色推送給前一個人員。

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; 
 
    }); 
 
    
 
\t // Construct new array 
 
    var newArr = []; 
 
    
 
\t for (i=0; i<arr.length; i++) { 
 
\t \t if (arr[i-1] && (arr[i].name == arr[i-1].name)) { 
 
\t \t \t newArr[newArr.length-1].role.push(arr[i].role) 
 
\t \t } else { 
 
\t \t \t newArr.push({name: arr[i].name, role: [arr[i].role]}); 
 
\t \t } 
 
\t } 
 
    
 
\t return newArr; 
 
} 
 

 
console.log(reconstruct(people));

相關問題