2015-02-09 144 views
0

我想創建一個新的JSON對象(selectedProductAttributes)當第二JSON對象的內容(selectedProductAttributesNames)是針對第3對象compaired所創建( allProductAttributes)!爲了更詳細地解釋我具有低於通過對比另外兩個JSON創建JSON對象對象

第一種稱爲allProductAttributes是包含表單字段

$scope.allProductAttributes = [ 
     { 
      name: 'postcode', 
      title: 'Postcode', 
      required: true, 
      type: 'text', 
      max: '10', 
      placeholder: 'Enter a postcode' 
     }, 
     { 
      name: 'Term', 
      title: 'Contract term', 
      required: true, 
      type: 'number', 
     }, 
     { 
      name: 'bandwidth', 
      title: 'bandwidth', 
      type: 'select', 
      options: [ 
       {id: 10, name: '10 mb/s'}, 
       {id: 100, name: '100 mb/s'}, 
       {id: 1000, name: '1000 mb/s'}, 
       {id: 10000, name: '10000 mb/s'} 
      ] 
     }, 
     { 
      name: 'service', 
      title: 'Service', 
      required: true, 
     } 

]

接下來JSON對象,不同的充屬性JSON對象一些實例中selectedProductAttributesNames,包含用戶想要從allProductAttributes中選擇的表單域列表

$scope.selectedProductAttributesNames = [ 
"postcode", 
"service" 
] 
從上面的例子

所以,當用戶請求「郵政編碼」和在selectedProductAttributesNames「服務」,應含有從allProductAttributes表單字段屬性來創建一個新的JSON對象...

$scope.selectedProductAttributes = [ 
    { 
      name: 'postcode', 
      title: 'Postcode', 
      required: true, 
      type: 'text', 
      max: '10', 
      placeholder: 'Enter a postcode' 
     }, 
    { 
      name: 'service', 
      title: 'Service', 
      required: true, 
     } 
] 

I」對不起,如果我讓你困惑。有誰知道我能做到這一點?謝謝

+1

使用'Array.filter'。 – Halcyon 2015-02-09 17:04:31

回答

2

除非你想另起爐竈,你可以使用下劃線和做這樣的事情:

$scope.selectedProductAttributes = _.compact($scope.allProductAttributes.map(function (item) { 
    return _.contains($scope.selectedProductAttributesNames, item.name) ? 
      item : false})) 

如果你不關心支持IE 6,7也不8,和唐」要使用任何外部庫,您可以這樣做:

$scope.selectedProductAttributes = $scope.allProductAttributes.filter(function (item) { 
    var validated = false, i, length = $scope.selectedProductAttributesNames.length; 
    for (i = 0 ; i < length; i++) { 
     if (item.name == $scope.selectedProductAttributesNames[i]) 
      validated = true; 
    } 
    return validated 
}) 
+0

我並不熟悉'compact'方法,我更喜歡這個方法,因爲它不會改變數據。 – 2015-02-09 17:15:32

+0

太好了 - 謝謝 – 2015-02-10 11:33:42

0

如果你有能力改變屬性源對象一點點以匹配下面的樣式,使用字典樣式訪問你的對象和循環會得到你正在尋找的東西。

$scope.selectedProductAttributeNames = { 
    'postcode' : { 
     'name': 'postcode', 
     /// remaining things here 
    }, 
    /// remaining attributes here 
}; 

for (var i = 0, l= $scope.selectedProductAttributeNames.length; i < l; i++) { 
    $scope.selectedProductAttributes[x[i]] =  
    $scope.selectedProductAttributeNames[x[i]]; 
} 
+0

感謝您的回答 – 2015-02-10 11:34:08