如何过滤/搜索多维对象数组?

时间:2014-06-18 23:11:33

标签: javascript arrays javascript-objects

我有如下数据结构:

var options = [{
        name: "Option One",
        foo: "bar",
        values: [{
            name: "Value One",
            value: "Value",
            options: [{
                name: "Option Two",
                values: [{
                    name: "Value Two",
                    value: "Value",
                    options: []
                }]
            }]
        }]
    }, {
        name: "Option Three",
        values: [{
            name: "Value Three",
            value: "Value",
            options: []
        }]
    }];

我需要压扁它,过滤掉我不想要的属性并保持每个对象深度的知识,如下面的数据结构:

var flattenedFilteredOptions = [{
        depth: 0,
        name: "Option One",
        values: [{
            name: "Value One",
            value: "Value"
        }]
    }, {
        depth: 1,
        name: "Option Two",
        values: [{
            name: "Value Two",
            value: "Value"
        }]
    }, {
        depth: 0,
        name: "Option Three",
        values: [{
            name: "Value Three",
            value: "Value"
        }]
    }];

所以基本上我只想要输出中的名称,值和值的属性。有人能指出我正确的方向甚至开始这样的事情,或者有人有解决方案吗?

1 个答案:

答案 0 :(得分:0)

谢谢大家,这就是我所做的,请记住配置要过滤的属性不是可配置的,递归有效:

   function flattenOptions(optionsArray, depth, flattenedOptions) {
        depth = depth || 0;
        flattenedOptions = flattenedOptions || [];

        for (var i = 0; i < optionsArray.length; i++) {
            var option = optionsArray[i];
            var nextDepth = depth + 1;
            var flattenedOption = {
                depth: depth,
                name: option.name,
                values: flattenValues(option.values, nextDepth, flattenedOptions)
            };

            flattenedOptions.push(flattenedOption);
        }

        return flattenedOptions;
    }

    function flattenValues(valuesArray, nextDepth, flattenedOptions) {
        var values = [];

        for (var i = 0; i < valuesArray.length; i++) {
            var value = valuesArray[i];

            values.push({
                name: value.name,
                value: value.value
            });
            if (value.options.length > 0) {
                flattenOptions(value.options, nextDepth, flattenedOptions);
            }
        }

        return values;
    }