【问题标题】:filter array and return the object containing the closest strings inside array inside an object, inside another array过滤数组并返回包含对象内数组内最近字符串的对象,在另一个数组内
【发布时间】:2020-10-20 02:30:12
【问题描述】:

我想返回包含对象内数组内最近字符串的对象,在另一个数组内, 我的indexOf() 只返回确切的字符串为真。

我尝试将indexOf() 替换为march()matches()includes() 没有任何效果。

请指教

let SellerList = [
  { supplyList: ["apple", "orange", "red apple"] },
  { supplyList: ["apple juice", "drink", "green apple", "dream app"] },
  { supplyList: ["lamp", "dog", "cat", "man"] }
];

let stringToMatch = "app";

let filteredList = SellerList.filter(
  (txt) => txt.supplyList.indexOf(stringToMatch) !== -1
);

我希望的输出是包含最近字符串的所有对象,例如:

[
  { supplyList: ["apple", "orange", "red apple"] },
  { supplyList: ["apple juice", "drink", "green apple", "dream app"] }
];

【问题讨论】:

  • 来自搜索词app,它显示了预期的结果,为什么?数组SellerList 中是否有多个对象?
  • @Mario 是的,我有不止一个
  • 对于stringToMatch = "app" 的预期输出是什么?
  • @Mario 所有包含最接近字符串的对象,例如:查看我的问题我用预期的输出示例编辑它

标签: javascript arrays string filter


【解决方案1】:

您在一个对象内有一个数组,在另一个数组内,因此您想定位该内部数组并在其上调用过滤器:

let SellerList = [{
  supplyList: ['apple', 'orange', 'red apple']
}];

let stringToMatch = 'app';

let filteredList = SellerList[0].supplyList.filter(txt => txt.indexOf(stringToMatch) !== -1);

console.log(filteredList)

【讨论】:

  • 谢谢,但是当我有多个对象时,我该怎么做呢?在与另一个内部字符串数组的数组中?
【解决方案2】:

请尝试以下解决方案

let SellerList = [
  { supplyList: ["apple", "orange", "red apple"] },
  { supplyList: ["apple juice", "drink", "green apple", "dream app"] },
  { supplyList: ["lamp", "dog", "cat", "man"] },
];

let stringToMatch = "app";

let filteredList = SellerList.reduce((previousValue, currentValue) => {
  if (currentValue.supplyList.join().includes(stringToMatch)) {
    previousValue = [...previousValue, { supplyList: currentValue.supplyList }];
  }

  return previousValue;
}, []);

console.log(filteredList);

【讨论】:

    【解决方案3】:

    您应该尝试匹配 supplyLists 的内部字符串而不是数组本身。

    let SellerList = [ 
                         { supplyList: ['apple','orange','red apple'] },
                         { supplyList: ['apple juice','drink','green apple'] } 
                       ];
      
      let stringToMatch = 'app';
    
      let filteredList = SellerList.map(list => {
        
        return list.supplyList.filter(item => {
          return item.indexOf(stringToMatch) >= 0
        })
      
      });
      
      
      console.log(filteredList);

    【讨论】:

    • 谢谢,我如何重新计算包含最近字符串的对象?例如:{ supplyList: ['apple juice','drink','green apple'] } 我还用预期的输出编辑了我的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 2020-10-16
    • 2016-10-24
    相关资源
    最近更新 更多