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

标签 javascript json angularjs

我正在尝试创建一个新的 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/

相关文章:

javascript - 测试未遵守 "beforeEach"内的超时

json - 服务器返回 text/html header 而不是 application/json header

MySQL 分组并合并 JSON 值

angularjs - ui-router 有时不会在 Internet Explorer > 9 中更改页面

javascript - 如何在按下 Enter 键时在自定义组件内执行 Angular ng-click 指令

javascript - 为什么我的 Angular 函数在无限循环中被调用?

javascript - HTML 简单下拉列表和结果

javascript - for 循环的 xhr 响应不起作用

javascript - jqgrid - 内联编辑,仅发布更改的数据

arrays - 如何按特定顺序连接 JSON 数组的两个值?