2016-08-11 89 views
0

我有一個如下對象的示例數組,我想要名稱爲Test的數組中的對象之一。如何使用下劃線按鍵查找數組中的對象

**Results: [ 
{ Name: "Test", 
    Age :21 
    ChildrenObj: 
}, 
{ Name: "Something else", 
    Age :21 
    ChildreObj 
}** 

我使用下面的代碼來找到它,它沒有返回我正確的數據

var names= (_un.find(data.Results, function(item) { 
     return item.Name= "Test"; 
    })); 

任何方向將不勝感激。

+2

'返回item.Name == 「測試」'平等的測試,不做分配。 – Will

+0

@非常感謝。愚蠢的錯誤,我做到了。這就是爲什麼我得到了所有的數據。 – kobe

+1

更好的是,最好使用===(3等於)。這也確保它們是相同的類型! 1 ==「1」是真實的,但1 ===「1」不是 – Kalman

回答

1

試試這個:

return item.Name == "Test"; 

你正在做的任務不是comparisson。

Results: [ 
{ Name: "Test", 
    Age :21 
    ChildrenObj: 
}, 
{ Name: "Something else", 
    Age :21 
    ChildreObj 
} 
1

您可以使用過濾器

results = [ 
{ Name : "Test", 
    Age : 21, 
    ChildrenObj : null 
}, 
{ Name : "Something else", 
    Age :21, 
    ChildrenObj : null 
}]; 
var names = results.filter(x => x.Name === "Test"); 
console.log(names); // [ { Name: 'Test', Age: 21, ChildrenObj: null } ] 
2

這裏有一個工作例子,只是爲了好玩。

var Results = [{ 
 
    Name: "Test", 
 
    Age: 21, 
 
    ChildrenObj: {} 
 
}, { 
 
    Name: "Something else", 
 
    Age: 21, 
 
    ChildrenObj: {} 
 
}]; 
 

 
var names = (_.find(Results, function(item) { 
 
    return item.Name == "Test"; 
 
})); 
 

 
console.log(names);
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

2

var data = [{ 
 
    Name: "Test", 
 
    Age :21 
 
}, 
 
{ Name: "Something else", 
 
    Age :22 
 
}]; 
 
    
 
    
 
console.log(_.findWhere(data, {Age: 22}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

相關問題