通过比较另外两个json对象来创建json对象

时间:2015-02-09 17:03:14

标签: javascript json angularjs

我正在尝试创建一个新的json对象( selectedProductAttributes ),该对象是在第二个json对象( selectedProductAttributesNames )的内容与第三个对象进行比较时创建的(的 allProductAttributes )!为了更详细地解释,我在下面有一些例子

第一个名为 allProductAttributes 的是一个json对象,它包含表单字段的不同属性

$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对象 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,
        }
]

对不起,如果我弄糊涂了你。有谁知道我怎么能做到这一点?感谢

2 个答案:

答案 0 :(得分: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
})

答案 1 :(得分: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]];
}
相关问题