javascript - 循环数组重新格式化数据结构

标签 javascript jquery

我想重新格式化数组,但结果不正确。 请先检查我的代码。

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);

在我的示例中有重复的房间类型 A 我想重新格式化

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; }

关于javascript - 循环数组重新格式化数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63408958/

相关文章:

jquery - knockout 内联编辑绑定(bind)

javascript - 如何使用 Javascript 检查正则表达式中的奇数反斜杠?

javascript - 当单个页面上有多个表单时提交单个表单

javascript - 无需超出页面即可更新数据库

javascript - ScalaJs 和 Javascript 是否可以替代 "implements"特征

php - 将 PHP 变量从 while 循环传递到 javascript 函数

javascript - 如何清除 JSON 的缓存

PHP 相当于这个 Javascript

javascript - 如何使用对象从对象数组javascript中删除它?

javascript - JQuery Mobile CSS 在 Jelly Bean 中将整个页面变黑