【问题标题】:How to get array of objects rather than array of arrays如何获取对象数组而不是数组数组
【发布时间】:2019-02-01 15:56:18
【问题描述】:

我正在尝试做一些映射来得到一个对象数组。

类似这样的:

但是我从下面的方法得到的是一个数组数组

this.service.getItems(this.id).pipe(
      switchMap(arr => {
        const userObservables = 
        arr.map(collects => this.afs.collection(`users`,
           (ref) => ref.where('someId', '==', collects.id)).valueChanges()
           .pipe(first())
        );
        return combineLatest(...userObservables)
            .pipe(
              map((...eusers) => {
                console.log(eusers[0]) //Should be array of objects
                arr.forEach((collect, index) => {
                  collect['username'] =  eusers[0][index]['displayName']['username'];
                  collect['first_name'] =  eusers[0][index]['displayName']['first_name'];
                  collect['last_name'] =  eusers[0][index]['displayName']['last_name'];
                  collect['avatar'] = eusers[0][index]['photoURL'];
              });
              console.log(arr)
              return arr;
            })
            );
      })
    )
    .subscribe(obj => console.log(obj));

我应该如何重写它以获得我想要的结果(对象数组)?

【问题讨论】:

  • 不是 rxjs 方面的专家,但也许可以查看 flatMap 并尝试用 flatMap 替换您的地图功能
  • 好的,我也试试.. @OleksandrFedotov

标签: javascript arrays rxjs


【解决方案1】:

JavaScript

concat() 方法用于合并两个或多个数组。这种方法 不会改变现有数组,而是返回一个新数组。

const array = [['1', '2'],['1'],['1','2','3']];
const newArray = [].concat.apply([], array);

然而 Lodash 和 Underscore 对这种行为也很好,更干净:

洛达什

https://lodash.com/docs/#flatten

将数组扁平化一层。

_.flatten([1, [2, [3, [4]], 5]]);
// => [1, 2, [3, [4]], 5]

我在 Angular 项目中使用过 lodash,它使用起来非常简单。

import * as _ from 'lodash'; 

let x = _.flatten(array.items);

npm 包:https://www.npmjs.com/package/lodash

下划线 (JS)

https://underscorejs.org/#flatten

扁平化嵌套数组(嵌套可以到任何深度)。如果你通过 浅,数组只会展平一个级别..

_.flatten([1, [2], [3, [[4]]]]);
// => [1, 2, 3, 4];

_.flatten([1, [2], [3, [[4]]]], true);
// => [1, 2, 3, [[4]]];

npm 包:https://www.npmjs.com/package/underscore

【讨论】:

    【解决方案2】:

    您可以只使用一个简单的 for 每个样式循环将所有内容推送到一个新数组中。

    const input = [[1], [1], [1]];
    const output = [];
    
    input.forEach(arr => arr.forEach(elem => output.push(elem)));
    

    【讨论】:

      猜你喜欢
      • 2020-03-01
      • 1970-01-01
      • 2021-02-11
      • 2014-12-10
      • 1970-01-01
      • 1970-01-01
      • 2020-03-28
      • 1970-01-01
      相关资源
      最近更新 更多