【问题标题】:nodejs how I filter an arrays of objectsnodejs我如何过滤对象数组
【发布时间】:2021-01-04 20:47:12
【问题描述】:

我有一个数组列表和这样的对象:

[
  [
    {
      address: 'x-x-x-x',
      listed: false
    }
  ],
  [
    {
      address: 'x-x-x-x',
      listed: false
    }
  ],
  [
    {
      address: 'x-x-x-x',
      listed: false
    }
  ],
  [
    {
      address: 'x-x-x-x',
      listed: false
    }
  ],
  [
    {
      address: 'x-x-x-x',
      listed: false
    }
  ],
  [
    {
      address: 'x-x-x-x',
      listed: true
    }
  ]
]

现在我想过滤所有列出的对象,但它不起作用,我尝试了库 lodash 并尝试了函数过滤器。但它不起作用。我做错了什么?

            results = await Promise.all(promiseArr);

            const data = lodash.filter(results, {
                listed: true
            });

            console.log(results);

【问题讨论】:

    标签: node.js arrays object


    【解决方案1】:

    不确定内部数组中是否会有多个元素,但这无论如何都可以。

    const yourArray = [
      [
        {
          address: 'x-x-x-x',
          listed: false
        },
        {
          address: '1-x-x-x',
          listed: true
        }
      ],
      [
        {
          address: '2-x-x-x',
          listed: true
        }
      ]
    ]
    
    const newArray = yourArray.reduce((previousValue, currentValue) => {
      const listedTrueObjects = currentValue.filter(obj => {
        return obj.listed === true
      })
      previousValue = previousValue.concat(listedTrueObjects)
      return previousValue
    }, [])
    
    console.log(newArray)
    
    

    编辑:没有看到您的较低代码...这应该可以工作。

    results = await Promise.all(promiseArr);
    
    const data = results.reduce((previousValue, currentValue) => {
      const listedTrueObjects = currentValue.filter(obj => {
        return obj.listed === true
      })
      previousValue = previousValue.concat(listedTrueObjects)
      return previousValue
    }, [])
    
    console.log(results);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      • 2020-01-27
      相关资源
      最近更新 更多