0

There is an array of objects

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

I am trying to convert it into:

[  [{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}] 
]

How can I use underscore.js chain/map/pluck etc... function to get the flatten result in specified format in the cleanest way?

4 Answers 4

1

You could use Array#forEach and build the nested parts upon.

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

Sign up to request clarification or add additional context in comments.

Comments

1

You can use array's reduce like this

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)

Comments

1

I have done as you have requested but used plain ES6 instead of underscore.

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

Comments

1

Here's a solution using underscore:

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.