繁体   English   中英

尝试使用Lodash返回深层嵌套对象

[英]Trying to return a deep nested object with Lodash

我无法在StackoverlFlow上找到针对此问题的解决方案,并且我已经致力于此问题已有一段时间了。 这有点困难,所以请让我知道我是否应该提供更多信息。

我的问题:我有一个Lands的JSON对象,每个土地都有一个ID和与之关联的Blocks数组,并且blocks数组也具有ID的block。

预习:

var Lands = [{
                'LandId':'123',
                'something1':'qwerty',
                'something2':'qwerty',
                'Blocks': [
                    {
                        'id':'456',
                        'LandId':'123'
                    },
                    {
                        'BlockId':'789',
                        'LandId':'123'
                    }
                ]
            },
            ...More Land Objects];

注意 :数据不是按照我本来会设置的方式设置的,但是这是在一段时间之前完成的,因此我现在必须处理我所拥有的东西。

我试图编写一个lodash函数,该函数将获取我拥有的blockId并将其匹配,并从Blocks返回landId。

因此最终结果将是从块返回的LandId列表。

我正在使用类似的东西,但没有返回结果:

selectedLand = function(Lands, landIDs){
                return _.filter(Lands, function(land){
                    return land === landIDs[index];
                });
            };

我知道我正在以错误的方式处理此问题,并且想知道解决此问题的适当方法。 任何帮助深表感谢。

selectedLand = function(Lands, landIDs){
                return _.filter(Lands, function(land){
                    return land === landIDs[index];
                });
            };

请注意, index在此范围内没有任何定义,因此,除非使用外部定义的index发生lucky(?)事故,否则此函数将永远不会返回true。 每当您调用_.filter(someArr,function(){return false;})您都会得到[] 除了未定义的index外,这会严格比较Land对象与(可能是)landID中的字符串

我对您选择的确切要求尚不清楚,因此您可以定制此过滤器以适合您的需求。 函数滤波 lands通过检查阵列如果.blocks数组属性具有其中的一些.landID属性被包括landsID阵列。

最后,如果您想充分利用lodash (或我最喜欢的ramda.js ),我建议您坐下来阅读文档 听起来很无聊,但是75%的数据转换之争是知道工具箱中的内容。 请注意,该过程的英文说明几乎与示例代码(过滤器,有些包含)完全匹配。

 var Lands = [{ 'LandId': '123', 'something1': 'qwerty', 'something2': 'qwerty', 'Blocks': [{ 'id': '456', 'LandId': '123' }, { 'BlockId': '789', 'LandId': '123' }] } ]; // assuming lands is like the above example // and landIDs is an array of strings var selectLandsWithBlocks = function(lands, landIDs) { return _.filter(lands, function(land) { var blocks = land.Blocks; var blockHasALandId = function(block) { return _.includes(landIDs,block.LandId); }; return _.some(blocks, blockHasALandId); }); }; console.log(selectLandsWithBlocks(Lands,[])); console.log(selectLandsWithBlocks(Lands,['mittens'])); console.log(selectLandsWithBlocks(Lands,['123'])); 
 <script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM