改变对象数组

时间:2018-12-11 05:36:15

标签: javascript jquery

我有一个这样的对象数组...

[
{ id:1, t1_id: 345, t1_val: "small", t2_id: 456, t2_val: "med", t3_id: 146, t3_val: "lrg"  },
{ id:2, t1_id: 983, t1_val: "small", t2_id: 657, t2_val: "med", t3_id: 548, t3_val: "lrg"  },
{ id:3, t1_id: 479, t1_val: "small", t2_id: 256, t2_val: "med", t3_id: 326, t3_val: "lrg"  }
]

我正在尝试将此数组更改为类似这样的内容...

[
{ id:1, t1_id: 345, t1_val: "small"},
{ id:1, t2_id: 345, t2_val: "med" },
{ id:1, t3_id: 146, t3_val: "lrg"  },


{ id:2, t1_id: 983, t1_val: "small" },
{ id:2, t2_id: 657, t2_val: "med",},
{ id:2, t3_id: 548, t3_val: "lrg"  },

{ id:3, t1_id: 479, t1_val: "small"  },
{ id:3, t2_id: 256, t2_val: "med", },
{ id:3, t3_id: 326, t3_val: "lrg"  }
]

最有效的方法是什么?我看过this solution,但不确定在我的情况下如何实现?最好使用ES6解决方案。

1 个答案:

答案 0 :(得分:0)

function filterData(arr) {

  var rs = []
  arr.forEach(function(e) {

    rs.push({
      'id': e['id'],
      't1_id': e['t1_id'],
      't1_val': e['t1_val']
    });

    rs.push({
      'id': e['id'],
      't2_id': e['t2_id'],
      't2_val': e['t2_val']
    });

    rs.push({
      'id': e['id'],
      't3_id': e['t3_id'],
      't3_val': e['t3_val']
    });
  })

  return rs;
}

var x = [{
    id: 1,
    t1_id: 345,
    t1_val: "small",
    t2_id: 456,
    t2_val: "med",
    t3_id: 146,
    t3_val: "lrg"
  },
  {
    id: 2,
    t1_id: 983,
    t1_val: "small",
    t2_id: 657,
    t2_val: "med",
    t3_id: 548,
    t3_val: "lrg"
  },
  {
    id: 3,
    t1_id: 479,
    t1_val: "small",
    t2_id: 256,
    t2_val: "med",
    t3_id: 326,
    t3_val: "lrg"
  }
];

console.log(filterData(x))