0

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

1
  • 1
    Do you really need to use RxJS for this? Commented Jul 11, 2018 at 14:08

2 Answers 2

1

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);
  })
Sign up to request clarification or add additional context in comments.

Comments

0

You can use groupBy operator - it will group your data by object property

2 Comments

And how can I get next format? {'title': 'Planning', 'datasets': {data: [/* 1st item will be here*/]},
You can map as you want - ...groupBy(data).pipe(toArray()),map( mapFnToDesiredFormat ).... So, for example you have [{title: 'B2', name: "Sue"},{title: 'B2', name: "Frank"}] as first group. Map fn is (v) => ({title: v[0].title, datasets:{data:[v[0]]}}).

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.