开发者问题收集

javascript - 在对象数组中搜索字符串

2018-05-13
164

我想在对象数组中搜索字符串并返回匹配的对象。尝试在这里使用 es6

请找到以下代码:

// set of keys
const defConfigs = [{
    title: "Id",
    key: "id"
  },
  {
    title: "Tenant",
    key: "tenant"
  },
  {
    title: "Opened",
    key: "opened"
  },
  {
    title: "Title",
    key: "title"
  },
  {
    title: "Status",
    key: "status"
  },
  {
    title: "Priority",
    key: "priority"
  }
];

// items as array of objects
const items = [{
    id: "INC000000004519",
    title: "Follow-up after INC000000004507",
    description: null,
    urgency: "4-Low",
    severity: "4-Minor/Localized"
  },
  {
    id: "INC000000004515",
    title: "network drop:↵Network Element CVU042_Johnstown get unsynchronized↵Network Element CVU043_Redman",
    description: "Client network drop since 08:51 until 09:06, pleas…ork Element CVU045_North_Salem get unsynchronized",
    urgency: "3-Medium",
    severity: "3-Moderate/Limited"
  },
  {
    id: "INC000000004088",
    title: "not able to schedule GPEH in ABC",
    description: "Contact: [email protected]↵+14692669295↵…WCDMA, we are not able to schedule GPEH in ABC. I",
    urgency: "4-Low",
    severity: "4-Minor/Localized"
  },
  {
    id: "INC000000004512",
    title: "SR Updated - P3 - 2018-0427-0305 - xyz TELECOMMUNICATIONS ROMANIA S.R.L - Lost the  mng connect",
    description: null,
    urgency: "4-Low",
    severity: "4-Minor/Localized"
  },
  {
    id: "INC000000004414",
    title: "Acme incident 1 title",
    description: "Acme incident 1 description",
    urgency: "2-High",
    severity: "1-Extensive/Widespread"
  }
];


// trying to search for string in keys defined in defConfigs
items.filter(item =>
  defConfigs.forEach((def) => {
    if (def.key in item) {
      return (item[def.key].toString().toLowerCase().match('low').length > 1);
    }
  }));

// always throws an error Uncaught TypeError: Cannot read property 'length' of null
console.log(items);

这里有 3 个带有字符串“low”的对象,我希望代码返回第一个项目(其中“title”是“Fol low -up after”);但 match 永远不会返回。

如何在对象数组中搜索字符串并返回这些对象作为结果?

3个回答

如果您仔细观察,您会注意到:

  1. 您没有检查 .match 是否匹配(不匹配时返回 null ;测试 null.length 将引发错误)
  2. 您正在检查 match.length > 1 ... 您使用的语法将返回一个只包含一个项或 null 的数组
  3. 您缺少 .filter 的返回语句
  4. 您没有将 .filter 的返回值分配给任何变量

您需要执行以下操作:

var filteredItems = items.filter(function (item) {
    return defConfigs.some(function (def) {
        return (def.key in item)
            ? item[def.key].toString().toLowerCase().match('low') !== null
            : false;
    });
});
console.log(filteredItems);
Salman Arshad
2018-05-13

String.prototype.match() 函数如果没有匹配项,将返回 null ,因此您需要检查这种情况。接下来,您可以使用 Array.prototype.some() 函数来验证数组中至少有一个项目满足您的条件。例如:

items.filter(item =>
  // check if at least one key from `defConfigs` on `item` matches 'low'
  defConfigs.some((def) => {
    if (def.key in item) {
      const matched = item[def.key].toString().toLowerCase().match('low')
      // return true if item matched
      return !!matched
   }
   // match not found by default
   return false
}));
madox2
2018-05-13

String.prototype.match() 在未找到匹配项时将返回 null。如果希望它正常工作,则应严格将匹配结果与 null 进行比较。

您应该查看 Array.prototype.filter 。它返回一个新数组,并且不会修改作为参数传递的引用,您的原始项目是安全的(目前)。

Héctor Bordajandi
2018-05-13