我想重新格式化数组,但结果不正确。请先检查我的代码。
var items = [
{
room_type : 'Room A',
product_type : 'Product Type X',
formula : '10',
},
{
room_type : 'Room A',
product_type : 'Product Type Y',
formula : '20',
},
{
room_type : 'Room B',
product_type : 'Product Type Z',
formula : '30',
},
];
var new_items = [];
var obj = [];
$.each(items, function (i, data) {
var room_type = data.room_type;
var product_type = data.product_type;
var formula = data.formula;
obj[product_type] = [];
obj[product_type]['formula'] = formula;
new_items[room_type] = obj;
});
console.log(new_items);
在我的示例中,有重复的房间类型AI要重新格式化,例如
var new_items = [
'Room A' : {
'Product Type X' : {formula : '10'},
'Product Type Y' : {formula : '20'}
},
'Room B' : {
'Product Type Z' : {formula : '30'}
}
];
但是我的代码结果重复。谢谢你的帮助。
结果需要一个对象,然后从该对象添加属性。
var items = [{ room_type: 'Room A', product_type: 'Product Type X', formula: '10' }, { room_type: 'Room A', product_type: 'Product Type Y', formula: '20' }, { room_type: 'Room B', product_type: 'Product Type Z', formula: '30' }],
result = items.reduce((r, o) => {
['room_type', 'product_type']
.reduce((q, k) => q[o[k]] = q[o[k]] || {}, r)
.formula = o.formula;
return r;
}, {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句