2016-07-26 43 views
-2

在我的「var」中有一些id。該ID全部出現在具有id和名稱的靜態數據中。我想要做的是我必須找出我的ID的名稱,並單獨打印名稱。我正在嘗試使用許多Underscore js方法,但失敗了。有人可以澄清/建議我請。如何在JavaScript中比較兩個數據對象

var CatePeri =[]; 
 
var cate =[]; 
 
// var CateName=[]; 
 

 
    $scope.getCategories = function() { 
 
     for (var i = 0 ; i < mainSteps.length; i++) { 
 
      for (var j = 0; j<mainSteps[i].steps.length; j++) {     
 
       var CatePeri= mainSteps[i].steps[j].category; 
 
       cate.push(CatePeri); 
 
     // var CateName =_.findWhere(mainSteps[i].category, cate); 
 
     // var CateName =_.where(mainSteps[i].category, cate); 
 
       } 
 
     } 
 
      return cate; // It return Id's Now 
 
         // But i have to Return the name's of that id's

這裏

var CatePeri is having Whole Category id's with Names, 
     var cate is having Category id's alone, 

,而不是返回的ID我需要返回自己的名字。

回答

1

var CatePeri =[]; 
 
var cate =[]; 
 
// var CateName=[]; 
 

 
    $scope.getCategories = function() { 
 
     for (var i = 0 ; i < mainSteps.length; i++) { 
 
      for (var j = 0; j<mainSteps[i].steps.length; j++) {     
 
       var CatePeri= mainSteps[i].steps[j].category; 
 
       cate.push(CatePeri); 
 
     // var CateName =_.findWhere(mainSteps[i].category, cate); 
 
     // var CateName =_.where(mainSteps[i].category, cate); 
 
       } 
 
     } 
 
      return _.pick(_.values(cate), 'name'); // It return Id's Now 
 
         // But i have to Return the name's of that id's

+0

剛纔我試過了,它返回的{} ...空對象 –

+0

什麼是str美食。任何細節? –

+0

[「1」,「4」,「2」,「3」,「5」] –

0

我認爲,你有一個靜態JSON像下面

var staticJson ={ 
     id:'5rtf567', 
     name:'S' 
      } 

使用underscore.js _.where選項一樣,

// If you have the multiple object to find out the name put it the below code in `for` loop and try it 
    var nameOfId = _.where(staticJson ,{id:staticJson.id} 
    console.log('If you Want Whole Object',angular.toJson(nameOfId));  
    console.log('If you Want Name',angular.toJson(nameOfId.name));