String Operation In Nodejs
I have a scenario in nodeJS. I have an array of object like below which contains 2 attributes. result.items = [ { 'organizationCode': '
Solution 1:
const result = {};
result.items = [{
"organizationCode": "FP1",
"organizationName": "FTE Process Org"
},
{
"organizationCode": "T11",
"organizationName": "FTE Discrete Org"
},
{
"organizationCode": "M1",
"organizationName": "Seattle Manufacturing"
}
];
let inputText = "starts with M"; // example input textconst lastSpaceIndex = inputText.lastIndexOf(' ');
const secondPartOfInput = inputText.substring(lastSpaceIndex + 1).trim();
const firstPartOfInput = inputText.substring(0, lastSpaceIndex).trim().toLowerCase();
const filtered = result.items.filter(item => {
if (firstPartOfInput === "starts with")
return item.organizationCode.startsWith(secondPartOfInput) || item.organizationName.startsWith(secondPartOfInput);
if (firstPartOfInput === "ends with")
return item.organizationCode.endsWith(secondPartOfInput) || item.organizationName.endsWith(secondPartOfInput);
if (firstPartOfInput === "contains")
return item.organizationCode.includes(secondPartOfInput) || item.organizationName.includes(secondPartOfInput);
returnfalse;
})
console.log(filtered);
Solution 2:
Providing that you're filtering on the values of the items only and that the criteria is that the value startsWith
the search term, doing this:
result.items = [
{
"organizationCode": "FP1",
"organizationName": "FTE Process Org"
},
{
"organizationCode": "T11",
"organizationName": "FTE Discrete Org"
},
{
"organizationCode": "M1",
"organizationName": "Seattle Manufacturing"
}
];
let result = data.filter(item => {
let match = false;
Object.keys(item).forEach((k) => {
if (item[k].startsWith(input)) { // What is the search criteria?
match = true;
}
});
return match;
});
Should give you the result you want, but first, however, you have to figure out how you want to know what the user is asking for (startsWith
, endsWith
or contains
)
Post a Comment for "String Operation In Nodejs"