【问题标题】:Is there a way to filter part of the string from an array of object with a given array of string有没有办法用给定的字符串数组从对象数组中过滤部分字符串
【发布时间】:2021-05-10 14:42:55
【问题描述】:

在每个对象内部,我必须知道是否存在这种和平的字符串。我有这个自动生成的 numbs 数组,所以如果存在于 numbs 中,我的函数只能将分隔的数字(而不是 每个具有各自名称的数字)引入客户数组。

numbs = ["1","2","3","4","5","6","7","8","9","10"];
customers = [{name: "Pedro", number: "9"}, {name: "Ivo", number: "6,4,7,3"}];

function customerNames (arr) { 
    return numbs.filter(function(index) {
        return arr.some(function(numberCompared) {
            return numberCompared.number.includes(index)
        })
    });
}

console.log(customerNames(customers));

通过过滤客户数组,我创建了一个没有名称的新数组,但我不知道如何检查客户数组内部是否包括值“6”,我在互联网上找到的每个函数都类似于我的问题就是比较两个以不同方式排序的对象数组。

    numbs = ["1","2","3","4","5","6","7","8","9","10"];
    customers = [{name: "Pedro", number: "9"}, {name: "Ivo", number: "6,4,7,3"}];

    function customerNames (arr) { 
        return numbs.filter(function(index) {
            return arr.some(function(numberCompared) {
                return numberCompared.number.includes(index)
            })
        });
    }
    
console.log("Customers:", JSON.stringify(customerNames(customers)));

【问题讨论】:

  • 你期望什么输出?,我无法理解你的问题。
  • 我很困惑,你的最终目标是什么?是否根据 numbs 字段中的值通过每个对象中的数字字段过滤客户数组?或者您是否尝试通过其内部对象的值过滤客户数组。所以像 filter number == 9 会返回 {name: "Pedro", number: "9"}
  • @RahulKumar 我希望收到类似 customerNames = [{name: "Ivo", number: "3"}, {name: "Ivo", number: "4"}, {name: “Ivo”,编号:“6”},{name:“Ivo”,编号:“7”},{name:“Pedro”,编号:“9”}];
  • @cigolon 第一个,但真诚地,我宁愿提出这个疑问,这样您绘制的两个解决方案就会满足。但是现在你问我明白了在提问时缺乏客观性是多么不正确。
  • @pebueno 添加了返回所需输出的答案。

标签: javascript jquery ecmascript-6


【解决方案1】:

使用Array.reduce() 方法返回最终客户列表,并在方法内部检查数字includes 是否为客户编号。

numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
customers = [{ name: "Pedro", number: "9" },
{ name: "Ivo", number: "6,4,7,3" }];

function customerNames(customers, numbers) {
  return customers.reduce((list, customer) => {
    const cNums = customer.number.split(",").map(num => `${num}`)
    for (num of cNums) {
      if (numbers.includes(num)) {
        const customerObj = {
          name: customer.name,
          number: num
        }
        list.push(customerObj);
      }
    }
    return list;
  }, []);
}

console.log("Customers: ", (customerNames(customers, numbers)));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-04
    • 2019-10-24
    • 1970-01-01
    • 2021-12-15
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    • 2020-08-15
    相关资源
    最近更新 更多