簡體   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