UnderscoreJs:展平对象数组

时间:2016-07-06 18:39:07

标签: javascript underscore.js

有一个对象数组

[
  {a:1,val:[11,12]},
  {a:9,val:[21,22]},
  {a:7,val:[31,32]},
  {a:8,val:[41,42]}
]

我正在尝试将其转换为:

[  [{a:1,val:11},{a:9,val:21},{a:7,val:31},{a:8,val:41}] ,
   [{a:1,val:12},{a:9,val:22},{a:7,val:32},{a:8,val:42}] 
]

如何使用underscore.js链/ map / pluck等...函数以最干净的方式获取指定格式的展平结果?

4 个答案:

答案 0 :(得分:1)

您可以使用Array#forEach并在其上构建嵌套部分。



var data = [{ a: 1, val: [11, 12] }, { a: 9, val: [21, 22] }, { a: 7, val: [31, 32] }, { a: 8, val: [41, 42] }],
    result = [];

data.forEach(function (a, i) {
    a.val.forEach(function (b, j) {
        result[j] = result[j] || [];
        result[j][i] = { a: a.a, val: b };
    });
});

console.log(result);




答案 1 :(得分:1)

你可以像这样使用数组减少



var data = [
  {a:1,val:[11,12]},
  {a:9,val:[21,22]},
  {a:7,val:[31,32]},
  {a:8,val:[41,42]}
]

var result = data.reduce((res, next) => {
    res[0].push({a: next.a, val: next.val[0]});
    res[1].push({a: next.a, val: next.val[1]});
    return res;
}, [[], []])

console.dir(result)




答案 2 :(得分:1)

我按照您的要求完成了但是使用了普通的ES6而不是下划线。

var restructure = (x)=>
[x.map(({a,val})=>({a,val:val[0]})),x.map(({a,val})=>({a,val:val[1]}))]

var result = restructure([
  {a:1,val:[11,12]},
  {a:9,val:[21,22]},
  {a:7,val:[31,32]},
  {a:8,val:[41,42]}
])
//[[{"a":1,"val":11},{"a":9,"val":21},{"a":7,"val":31},{"a":8,"val":41}],[{"a":1,"val":12},{"a":9,"val":22},{"a":7,"val":32},{"a":8,"val":42}]]

答案 3 :(得分:1)

以下是使用下划线的解决方案:

var result = _.chain(data)
    .map(item => _.map(item.val, val => ({a: item.a, val})))
    .unzip()
    .value();

var data = [
  {a:1,val:[11,12]},
  {a:9,val:[21,22]},
  {a:7,val:[31,32]},
  {a:8,val:[41,42]}
]

var result = _.chain(data)
  .map( item => _.map(item.val, val => ({a: item.a, val})))
  .unzip()
  .value();

document.getElementById('result').textContent = JSON.stringify(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore.js"></script>

<p>
  <pre id="result"></pre>
</p>