2017-03-07 102 views
3

flatten,flattenDeep或flattenDodth lodash只接受數組。如何拼合嵌套的對象?使用lodash弄平嵌套對象

var data = { 
    "dates": { 
    "expiry_date": "30 sep 2018", 
    "available": "30 sep 2017", 
    "min_contract_period": [{ 
     "id": 1, 
     "name": "1 month", 
     "value": false 
    }, { 
     "id": 2, 
     "name": "2 months", 
     "value": true 
    }, { 
     "id": 3, 
     "name": "3 months", 
     "value": false 
    }] 
    }, 
    "price": { 
    "curreny": "RM", 
    "min": 1500, 
    "max": 2000 
    } 
} 

我想嵌套屬性是第一個層次,像EXPIRY_DATE應爲1級,不在日期,我認爲日期應該走了,就不再需要。我可以手動執行,使用map(),但我希望使用lodash來緩解任務。

+0

你可以舉例說明你希望輸出在任務完成後的樣子代碼嗎?說1級,並且事情'應該消失'可以混淆這個問題,一個例子會非常明確 –

回答

0

可以.merge().get()_.pick()結果:

var data = {"dates": {"expiry_date": "30 sep 2018","available": "30 sep 2017","min_contract_period": [{"id": 1,"name": "1 month","value": false}, {"id": 2,"name": "2 months","value": true}, {"id": 3,"name": "3 months","value": false}]},"price": {"curreny": "RM","min": 1500,"max": 2000}}, 
 
    result = _.merge(_.get(data, 'dates'), _.pick(data, 'price')); 
 

 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

4

一個最簡單的解決辦法是,合併與父嵌套對象,

_.merge(data, data.dates); 

這將帶入所有data.dates財產data。然後刪除data.dates

delete data.dates