coure2011
coure2011

Reputation: 42464

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

Upvotes: 2

Views: 558

Answers (2)

Monica Olejniczak
Monica Olejniczak

Reputation: 1156

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

Upvotes: 2

brk
brk

Reputation: 50326

Create a new array. Use forEach array method to get items from the old array

var newArray = [];
data.forEach(function(item){
 newArray.push({
  name:item.name,
  title:item.title
})

})

console.log(newArray)

JSFIDDLE

Upvotes: 0

Related Questions