【问题标题】:filter function not working in an Array using Node js过滤功能在使用 Node js 的数组中不起作用
【发布时间】:2021-07-15 12:57:39
【问题描述】:

我正在尝试过滤掉空数组,但它没有发生

  • 我试图比较我的数据库和文件名中存在的值
  • 我试过arr.filter(Boolean);
  • 即使我试过arr.filter((item)=>item)

PS:fileName 不是数组值,所以我将其转换为数组。

function checkDoc(data, childProduct, fileName, pathName, req, res) {
  return new Promise((resolve, reject) => {
    Document.findAll({
      raw: true,
      where: {
        product_id: childProduct.id,
      },
    })
      .then((productDoc) => {
        if (productDoc.length === 0) {
          return resolve(addDocument(data, childProduct, fileName, pathName));
        } else {
          let fileArray = [];
          fileArray.push(fileName);
          productDoc.forEach((singleProduct) => {
            let productValue = singleProduct.name;
            let unMatchedValues = fileArray.filter((value) =>
              productValue.includes(value)
            );
            let removedBoolean = unMatchedValues.filter((item) => item);
            console.log("Document Name: ", removedBoolean);
          });
        }
      })
      .catch(function (err) {
        return reject("Can't be added please try again :) " + err);
      });
  });
}
fileName:
ABC
PQR
XYZ
Installation and Configuration
Java
Node Js

它包含在 singleProduct.name 中的位置

[ABC]
[PQR]
[Installation and Configuration]
[XYZ]

附加输出图像:

预期输出:

matchedValue:
[`document name: ABC`]
[`document name: PQR`]
[`document name: Installation and configuration`]
[`document name: XYZ`]
unmatchedValue:
['Java']
[`Node Js`]

【问题讨论】:

  • 不清楚您要做什么。预期的输出是什么?
  • 嗨@thedude 我已经更新了我的问题,请看一下:)
  • 什么是fileName 在这个例子中运行?
  • 你应该在这里做一些调试。检查或记录代码中每个点的各种值,您很快就会发现出了什么问题。如果您以前没有使用过过滤器,那么您应该阅读基本介绍来过滤并在 Node REPL 中尝试一些测试。
  • Hello @jarmod 在我之前的函数中我使用了过滤器,但不知道为什么它在这里不起作用:)

标签: javascript node.js arrays promise nodes


【解决方案1】:

如果您询问如何过滤对象数组以删除名称为空的对象,这里有一个示例:

const team = [
  { name: 'max', age: 21 },
  { name: '', age: 19 },
  { name: 'james', age: 33 },
  { name: '', age: 30 },
];

// Log the entire team
console.log('Team:', team);

// Log only those team members with names
console.log('Team with names:', team.filter(x => x.name));

// Log only the names
console.log('Names:', team.filter(x => x.name).map(x => x.name));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-30
    • 1970-01-01
    相关资源
    最近更新 更多