需要将JavaScript代码更改为lodash

var templates = {
"category": {
    "findByName": {
        "method": "generic",
            "settings": {
            "baseURL": "some2"
        }
    }
},
"product": {
    "findByPartNumber": {
        "method": "generic",
            "settings": {
            "baseURL": "some1"
        }
    },
    "findByUniqueId": {
        "method": "generic",
        "settings": {
            "baseURL": "some1"
        }
    }
}
};


for ( var index in templates) {
    var module = templates[index];

    for ( var fileIndex in module) {

        if (module[fileIndex].method) {

            var dsSettings = module[fileIndex].settings;
           console.log(dsSettings)
        }
    }
}


结果:

{ baseURL: 'some2' }
{ baseURL: 'some1' }
{ baseURL: 'some1' }


Lodash代码:

_.forEach(templates, function(n, key) {
    var v = _.pluck(_.filter(n), 'settings');

    console.log(v);
});


结果:

[ { baseURL: 'some2' } ]
[ { baseURL: 'some1' }, { baseURL: 'some1' } ]


我正在寻找上面给出的lodash代码中的对象结果。请建议

最佳答案

单线如何:

settings = _(templates).map(_.values).flatten().pluck('settings').value()




var templates = {
    "category": {
        "findByName": {
            "method": "generic",
            "settings": {
                "baseURL": "some2"
            }
        }
    },
    "product": {
        "findByPartNumber": {
            "method": "generic",
            "settings": {
                "baseURL": "some1"
            }
        },
        "findByUniqueId": {
            "method": "generic",
            "settings": {
                "baseURL": "some1"
            }
        }
    }
};


settings = _(templates).map(_.values).flatten().pluck('settings').value()
document.write("<pre>" + JSON.stringify(settings,0,3));

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.5.0/lodash.js"></script>

关于javascript - 循环更改为lodash的Javascript,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29152422/

10-13 01:44