![](/img/trans.png)
[英]Transforming array of objects containing arrays into a unique object lookup with lodash
[英]Transforming array of objects using Lodash
我正在努力簡化一個錯綜復雜的結構。
我已經盡可能地簡化了它,並將其簡化為:
[
{'Cells':{'Results':[
{'Key':'ID','Value':123},
{'Key':'Color','Value':'Red'},
{'Key':'Direction','Value':'West'}
]}},
{'Cells':{'Results':[
{'Key':'ID','Value':456},
{'Key':'Color','Value':'Green'},
{'Key':'Direction','Value':'East'}
]}}
]
我的lodash缺乏技能,我需要幫助將上述內容轉化為:
[
{'ID':123, 'Color':'Red', 'Direction':'West'},
{'ID':456, 'Color':'Green', 'Direction':'East'}
]
我應該注意,順便說一下,按鍵的數量因對象而異。 至少,它可能只有ID,但有些可能比示例中的那些更多。
在普通的Javascript中,您可以使用兩個嵌套循環。
var array = [{ 'Cells': { 'Results': [{ 'Key': 'ID', 'Value': 123 }, { 'Key': 'Color', 'Value': 'Red' }, { 'Key': 'Direction', 'Value': 'West' }] } }, { 'Cells': { 'Results': [{ 'Key': 'ID', 'Value': 456 }, { 'Key': 'Color', 'Value': 'Green' }, { 'Key': 'Direction', 'Value': 'East' }] } }], condensed = array.map(function (a) { var o = {}; a.Cells.Results.forEach(function (b) { o[b.Key] = b.Value; }); return o; }); console.log(condensed);
這樣的事應該做(雖然我不確定它比普通的javascript更好)
_.chain(array)
.pluck('Cells')
.pluck('Results')
.map(function (value) { return _.object(_.map(value, _.values)); })
.value()
使用Lodash的解決方案:
var result = _.chain(data)
.map('Cells.Results')
.map(res => _.zipObject(_.map(res,"Key"), _.map(res,"Value")))
.value();
這是使用lodash fp的另一種選擇。
var result = map(compose(
mapValues('Value'),
keyBy('Key'),
iteratee('Cells.Results')
))(data);
var data = [{ 'Cells': { 'Results': [{ 'Key': 'ID', 'Value': 123 }, { 'Key': 'Color', 'Value': 'Red' }, { 'Key': 'Direction', 'Value': 'West' }] } }, { 'Cells': { 'Results': [{ 'Key': 'ID', 'Value': 456 }, { 'Key': 'Color', 'Value': 'Green' }, { 'Key': 'Direction', 'Value': 'East' }] } }]; var { compose, map, iteratee, keyBy, mapValues } = _; var result = map(compose( mapValues('Value'), keyBy('Key'), iteratee('Cells.Results') ))(data); document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script> <script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.fp.js"></script>
還有另一個答案,使用map和reduce
var initial_array=[ {'Cells':{'Results':[ {'Key':'ID','Value':123}, {'Key':'Color','Value':'Red'}, {'Key':'Direction','Value':'West'} ]}}, {'Cells':{'Results':[ {'Key':'ID','Value':456}, {'Key':'Color','Value':'Green'}, {'Key':'Direction','Value':'East'} ]}} ]; function mergeObj(accumulator,current){ accumulator[current['Key']]=current['Value']; return accumulator; } function getResults(obj){ return obj.Cells.Results.reduce(mergeObj,{}); } var transformed_array=_(initial_array).map(getResults).value(); console.log(transformed_array);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.