I need to convert the the init array to final array preferably using lodash.
initArray = [
{
"date":"2017-08-15",
"data":[
{
"color":"orange",
"count":100
},
{
"color":"green",
"count":101
}
]
},
{
"date":"2017-08-14",
"data":[
{
"color":"orange",
"count":102
},
{
"color":"green",
"count":103
}
]
}
]
finalArray = [
{
"color":"orange",
"data":[
100,
102
]
},
{
"color":"green",
"data":[
101,
103
]
}
]
I need to convert the the init array to final array preferably using lodash.
initArray = [
{
"date":"2017-08-15",
"data":[
{
"color":"orange",
"count":100
},
{
"color":"green",
"count":101
}
]
},
{
"date":"2017-08-14",
"data":[
{
"color":"orange",
"count":102
},
{
"color":"green",
"count":103
}
]
}
]
finalArray = [
{
"color":"orange",
"data":[
100,
102
]
},
{
"color":"green",
"data":[
101,
103
]
}
]
Share
Improve this question
edited Aug 18, 2017 at 2:15
Dij
9,8184 gold badges20 silver badges35 bronze badges
asked Aug 18, 2017 at 2:15
Sumit DhamejaSumit Dhameja
1412 silver badges9 bronze badges
1
- 1 lodash puzzles are fun and all, but next time try to explain what you tried and why it didn't work. – aaaaaa Commented Aug 18, 2017 at 3:42
2 Answers
Reset to default 5This way seems like the lodash calls make sense to me.
// var _ = require('lodash')
initArray = [
{
"date":"2017-08-15",
"data":[
{
"color":"orange",
"count":100
},
{
"color":"green",
"count":101
}
]
},
{
"date":"2017-08-14",
"data":[
{
"color":"orange",
"count":102
},
{
"color":"green",
"count":103
}
]
}
]
result = _(initArray)
//.map('data')
//.flatten()
.flatMap('data') // instead of .map('data').flatten()
.groupBy('color')
.map((item, key) => ({
color: key,
count: _.map(item, 'count')
}))
.value()
console.log(result)
<script src="https://cdn.jsdelivr/lodash/4/lodash.min.js"></script>
you can use reduce
to flatten the original array, so that all data arrays are on same level. Then use _.transform to get a temp object mapping colors to array of their counts. and then you can push things to finalArray using forEach.
var initArray = [
{
"date":"2017-08-15",
"data":[
{
"color":"orange",
"count":100
},
{
"color":"green",
"count":101
}
]
},
{
"date":"2017-08-14",
"data":[
{
"color":"orange",
"count":102
},
{
"color":"green",
"count":103
}
]
}
];
var finalArray = [];
var temp = _.transform(initArray.reduce((a,b) => a.data.concat(b.data)),
(r, v) => (r[v.color] || (r[v.color] = [])).push(v.count), {});
_.forEach(temp, (v,k) => finalArray.push({color:k, count:v}));
console.log(finalArray);
<script src="https://cdn.jsdelivr/lodash/4/lodash.min.js"></script>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745459257a4628630.html
评论列表(0条)