[英]Transform objects to array using lodash
我想將對象轉換為數組格式。 輸入對象是
{
"index": {
"0": 40,
"1": 242
},
"TID": {
"0": "11",
"1": "22"
},
"DepartureCity": {
"0": "MCI",
"1": "CVG"
},
"ArrivalCity": {
"0": "SFB",
"1": "LAS"
},
"Price": {
"0": 90,
"1": 98
}
}
而預期的產出是
[
{
"index": 40,
"TID": "11",
"DepartureCity": "MCI",
"ArrivalCity": "SFB",
"Price": 90
},
{
"index": 242,
"TID": "22",
"DepartureCity": "CVG",
"ArrivalCity": "LAS",
"Price": 98
}
]
我嘗試使用for循環,但它變得越來越復雜。 如果有人可以幫助我,那將非常感激。
這是一種lodash
方法
_.merge([], ..._.map(obj, (v, k) => _.mapValues(v, ev=> ({[k]:ev}))))
let inputObj = { "index": { "0": 40, "1": 242 }, "TID": { "0": "11", "1": "22" }, "DepartureCity": { "0": "MCI", "1": "CVG" }, "ArrivalCity": { "0": "SFB", "1": "LAS" }, "Price": { "0": 90, "1": 98 } }; let res = _.merge([], ..._.map(inputObj, (v, k) => _.mapValues(v, ev=> ({[k] :ev})))); console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
嘗試將entries
reduce
到一個對象數組中,迭代內部對象的每個值:
const input={"index":{"0":40,"1":242},"TID":{"0":"11","1":"22"},"DepartureCity":{"0":"MCI","1":"CVG"},"ArrivalCity":{"0":"SFB","1":"LAS"},"Price":{"0":90,"1":98}} const output = Object.entries(input).reduce((a, [key, obj]) => { Object.values(obj).forEach((val, i) => { if (!a[i]) a[i] = {}; a[i][key] = val; }); return a; }, []); console.log(output);
您可以將Object.keys
與reduce
結合使用
let object = { "index": { "0": 40, "1": 242 }, "TID": { "0": "11", "1": "22" }, "DepartureCity": { "0": "MCI", "1": "CVG" }, "ArrivalCity": { "0": "SFB", "1": "LAS" }, "Price": { "0": 90, "1": 98 } } result = Object.keys(object['index']).map(function(key){ return Object.keys(object).reduce(function(obj, item){ obj[item] = object[item][key]; return obj; }, {}); }); console.log(result);
您可以將內部值映射到相應的索引。
var data = { index: { 0: 40, 1: 242 }, TID: { 0: "11", 1: "22" }, DepartureCity: { 0: "MCI", 1: "CVG" }, ArrivalCity: { 0: "SFB", 1: "LAS" }, Price: { 0: 90, 1: 98 } }, result = Object .entries(data) .reduce( (r, [k, o]) => Object .entries(o) .map(([i, v]) => Object.assign(r[i] || {}, { [k]: v })), [] ); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
使用lodash,您只需要使用_.reduce()
和_.forEach()
方法,如下所示:
const result = _.reduce(Object.entries(object), function(a, [key, obj]){
_.forEach(Object.values(obj), function(val, i){
if (!a[i]) a[i] = {};
a[i][key] = val;
});
return a;
}, []);
演示:
const object = { "index": { "0": 40, "1": 242 }, "TID": { "0": "11", "1": "22" }, "DepartureCity": { "0": "MCI", "1": "CVG" }, "ArrivalCity": { "0": "SFB", "1": "LAS" }, "Price": { "0": 90, "1": 98 } }; const result = _.reduce(Object.entries(object), function(a, [key, obj]){ _.forEach(Object.values(obj), function(val, i){ if (!a[i]) a[i] = {}; a[i][key] = val; }); return a; }, []); console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.core.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.