Reputation: 3914
I have the next input array. It can have different phases.
[
{
"id": 1,
"phase": "Planning",
},
{
"id": 2,
"phase": "Planning",
},
{
"id": 3,
"phase": "Done",
}
]
Based on phases I want to convert it to array with next format.
[{title: 'Planning',
datasets: {data: [/* 1st item will be here*/]},
{data: [/* 2nd item will be here*/]}]},
{title: 'Done',
datasets: [{data: [/* 1st item will be here*/]}]
}
];
How can I do this?
Thanks in advance
Upvotes: 0
Views: 303
Reputation: 762
You can use groupBy operator - it will group your data by object property
Upvotes: 0
Reputation: 5224
Not sure why you need rxjs for this, you can achieve it using only javascript. Here's a ES6 implementation :
let input = [
{
"id": 1,
"phase": "Planning",
},
{
"id": 2,
"phase": "Planning",
},
{
"id": 3,
"phase": "Done",
}
]
let response = {};
input.forEach(phaseObj=> {
if(!!response[phaseObj["phase"]])
response[phaseObj["phase"]].push({data: phaseObj})
else
response[phaseObj["phase"]] = [{data: phaseObj}]
})
response = Object.keys(response).map( key=> { return {title: key, datasets : response[key]}});
console.log(response)
if you really insist on using rxjs, you can do something like :
let response = {};
Rx.Observable.from(input).map(phaseObj=> {
if(!!response[phaseObj["phase"]])
response[phaseObj["phase"]].push({data: phaseObj})
else
response[phaseObj["phase"]] = [{data: phaseObj}]
})
.toArray()
.subscribe( ()=> {
response = response = Object.keys(response).map( key=> { return {title: key, datasets : response[key]}});
console.log(response);
})
Upvotes: 1