我正在尝试创建一个新的 json 对象 (selectedProductAttributes),该对象是在将第二个 json 对象 (selectedProductAttributesNames) 的内容与第三个对象 (selectedProductAttributesNames) 进行比较时创建的所有产品属性)!为了更详细地解释,我在下面提供了一些示例
第一个名为 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 中请求“邮政编码”和“服务”时,应创建一个新的 json 对象,其中包含 allProductAttributes 中的表单字段属性...
$scope.selectedProductAttributes = [
{
name: 'postcode',
title: 'Postcode',
required: true,
type: 'text',
max: '10',
placeholder: 'Enter a postcode'
},
{
name: 'service',
title: 'Service',
required: true,
}
]
如果我让你感到困惑,我很抱歉。有谁知道我怎样才能实现这一目标?谢谢
最佳答案
除非你想重新发明轮子,否则你可以使用下划线并执行类似的操作:
$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
})
关于javascript - 通过比较另外两个 json 对象来创建一个 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28415188/