2015-02-09 147 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