更优雅的方式来获取名称的嵌套对象属性?

时间:2013-02-15 09:16:04

标签: javascript node.js underscore.js

我有这个工作代码,它从JS对象中检索对象属性的名称(不幸的是!)超出了我的范围。所以我无法改变这个对象的构建方式。但我想(并且确实)将属性的名称(标记为true)提取为数组,以便能够更轻松地处理此对象。

对象:

{
    group1: {
        foo: true,
        itemFoo: "Name of foo", // This is what I want, because foo is true
        bar: false,
        itemBar: "Name of bar", // I dont want this, bar is false
        // ...
    },
    group2: {
        baz: true,
        itemBaz: "Name of baz", // I want this too
        // ...
    },
    uselessProp1: "not an object",
    // ...
}

工作代码:

var items = [];

for (var m in obj) {
    if (typeof obj[m] == 'object') {
        for (var n in obj[m]) {
            if (obj[m][n] === true) {
                items.push(obj[m]['item' + (n.charAt(0).toUpperCase() + n.slice(1))]);
            }
        }
    }
}

我的问题是:有人知道使用underscore.js或plain node.js或任何其他库实现此遍历的更优雅方式吗?我使用_.filter进行了实验,但没有提出解决方案。

3 个答案:

答案 0 :(得分:1)

这样的东西?

var result = [];
_.chain(obj).filter(_.isObject).each(function(t) {
    _(t).each(function(val, key) {
        if(val === true)
            result.push(t['item' + key.charAt(0).toUpperCase() + key.substr(1)])
    })
})

答案 1 :(得分:1)

这是我到目前为止的解决方案:

http://jsfiddle.net/kradmiy/28NZP/

var process = function (obj) {
var items = [];

var objectProperties = _(obj).each(function (rootProperty) {
    // exit from function in case if property is not an object
    if (!_(rootProperty).isObject()) return;

    _(rootProperty).each(function (value, key) {
        // proceed only if property is exactly true
        if (value !== true) return;
        var searchedKey = 'item' + (key.charAt(0).toUpperCase() + key.slice(1));
        // check that parent has this property...
        if (rootProperty.hasOwnProperty(searchedKey)) {
            // ...and push that to array
            items.push(rootProperty[searchedKey]);
        }
    });
});

  return items;
};

答案 2 :(得分:1)

我想指出一些事情:

Micha’s Golden Rule
Micha Gorelick, a data scientist in NYC, coined the following rule:
Do not store data in the keys of a JSON blob.

您的JSON应该使用:

{//group1
  groupname:"group1",
  items :[
    {//item1
       itemcheck:true,
       itemname:'itemBar'
    },
    ...
  ]
},
...

如果将itemname存储在key中。遍历JSON时会遇到问题,因为'itemFoo'将使用'foo'(间接)来获取其值。您的数据结构是这里的问题。搜索您的JSON很棘手。遵循规则后,您的代码将自动优雅。

相关问题