I would like to search for a string in array of objects and returns objects that matches. Trying to use es6 here.
Please find below code:
// 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);
Here, there are 3 objects with string "low" and I expect the code to return the first item (where the "title" is "Follow-up after"); but match never returns.
How do I search for a string in array of objects and return those objects as a result ?
.match('low').lengthwill throw if no match is found. Also note thatdef.key in itemis false for all of your examples.foreachloop and stringify each object is the array. The do a regexmatch str.match('low'). If it returns true then return that itemdefConfig. But string 'low' is there intitlein one of the objects.