coure2011 coure2011 - 3 months ago 14
Javascript Question

combining array objects into single object

Using Rxjs 5.0, I have an object like this

var data = [
{name: 'abc', title: 'zzz', data: '', id: ''},
{name: 'abc1', title: 'zzz1', data: '', id: ''},
{name: 'abc2', title: 'zzz2', data: '', id: ''},
{name: 'abc3', title: 'zzz3', data: '', id: ''}
]


I want to simple map it, to retain just name and tile. So did something like this

Rx.Observable.from(data)
.map(item => return {name: item.name, title: item.title};)
.subscribe(items => console.log('Final OBJ:' + JSON.stringify(items)));


On console I am getting items on multiple line i.e. subscribe is running 4 times. I want to run subscribe only once with one complete object containing data with only name and title fields.

Expected output on console is:

Final OBJ: [{name: 'abc', title: zzz},{name: 'abc1', title: zzz1},{name: 'abc2', title: zzz2},{name: 'abc3', title: zzz3}]

Answer

You can simply have:

Rx.Observable.from(data)
  .reduce((arr, item, idx, source) => {
    arr.push({
      name: item.name,
      title: item.title
    });
    return arr;
  }, [])
  .subscribe(items => console.log(JSON.stringify(items)));

JS Bin example

Edit: It seems that combineAll should do the trick.

Rx.Observable.from(data)
  .map(item => {
    return Rx.Observable.of({
      name: item.name,
      title: item.title
    });
  })
  .combineAll()
  .subscribe(items => console.log(JSON.stringify(items)));

JS Bin Example