簡體   English   中英

nodejs對象中的字符串操作

[英]String operation in nodejs Objects

我在nodeJS中有一個場景。

我有一個包含元素數量和數組的 object

var Obj = {
  count: 3,
  items: [{
      "organizationCode": "FP1",
      "organizationName": "FTE Process Org"
    },
    {
      "organizationCode": "T11",
      "organizationName": "FTE Discrete Org"
    },
    {
      "organizationCode": "M1",
      "organizationName": "Seattle Manufacturing"
    }
  ]
};

場景是這樣的。 我必須根據標准過濾結果。 如果organizationCodeorganizationName以特定字符starts with特定字符ends withcontains特定單詞,我已打印 output。 例如,如果用戶輸入starts with M開頭或starts with "M"應該返回

{
  "organizationCode": "M1",
  "organizationName": "Seattle Manufacturing"
}

如果用戶輸入以 org 結尾,則

{
  "organizationCode": "FP1",
  "organizationName": "FTE Process Org"
}, {
  "organizationCode": "T11",
  "organizationName": "FTE Discrete Org"
},

如果它輸入contains 11那么下面應該返回。

{
  "organizationCode": "T11",
  "organizationName": "FTE Discrete Org"
},

我有成千上萬的記錄。 我正在尋找獲得 output 的優化方法。 我是NodeJs的新手,所以很難完成它。

先說第一件事。 這里有一些你可以使用的字符串函數:

endsWith "some string".endsWith('string')

startsWith "some string".startsWith('some')

包括"some string".includes('ome')

您可以將 object 與 Object.values() 進行轉換。

但如果我這樣做,我可能會像下面這樣,

// I'm assuming in the nodejs you would have some variables to search for
// like whereToSearch and whatToSearch lets say

var arrToSearch = [
  { organizationCode: "FP1", organizationName: "FTE Process Org" },
  { organizationCode: "T11", organizationName: "FTE Discrete Org" },
  { organizationCode: "M1", organizationName: "Seattle Manufacturing" },
];

function search(arr, whereToSearch, whatToSearch) {
  return arr.filter(
    (ch) =>
      ch.organizationCode[whereToSearch](whatToSearch) ||
      ch.organizationName[whereToSearch](whatToSearch)
  );
}

console.log(search(arrToSearch, "endsWith", "11"));

// We can also send the array to function so in this case your object is here
var object = {
  count: 3,
  items: [
    {
      organizationCode: "FP1",
      organizationName: "FTE Process Org",
    },
    {
      organizationCode: "T11",
      organizationName: "FTE Discrete Org",
    },
    {
      organizationCode: "M1",
      organizationName: "Seattle Manufacturing",
    },
  ],
};
//and what you can do with this is

console.log(search(object.items, "startsWith", "FTE"));

您可以將Array.filterString.startsWithString.includesString.endsWith結合使用。

您可以使用數組過濾器,通過所有元素 go 並根據需要處理它們。

還要檢查一個字符串是否包含另一個字符串,您可以對其使用不敏感的匹配。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

 var Obj = { count: 3, items: [ { organizationCode: "FP1", organizationName: "FTE Process Org", }, { organizationCode: "T11", organizationName: "FTE Discrete Org", }, { organizationCode: "M1", organizationName: "Seattle Manufacturing", }, ], }; const filter = (starts_with, ends_with, contains) => { const result = Obj.items.filter(item => { if(starts_with){ return ( item.organizationCode[0].toLowerCase() === starts_with.toLowerCase() || item.organizationName[0].toLowerCase() === starts_with.toLowerCase() )? true: false } else if(ends_with) { return ( item.organizationCode[item.organizationCode.length].toLowerCase() === ends_with.toLowerCase() || item.organizationName[item.organizationName.length].toLowerCase() === ends_with.toLowerCase() )? true: false } else { return ( item.organizationCode.match(contains,'i') || item.organizationName.match(contains,'i') )? true: false } }); return result; }; console.log(filter("F",null,null)); // test run

這是一個簡單的解決方案,最初分析用戶條件並過濾您的列表。

它有幾個改進點,但這是一個好的開始。

 const analyzeCond = condition => { let conditionParts = condition.split(' ').filter(str => str;== ''). if (conditionParts;length < 3) { return null. } // Check field const fieldName = conditionParts;shift(), if (.['organizationCode'; 'organizationName'].includes(fieldName)) { return null; } // Check operator const operator = conditionParts,shift(). if (['starts'. 'ends'];includes(operator)) { const withWord = conditionParts;shift(); if (withWord.== 'with') { return null; } } else if (operator,== 'contains'){ return null, } const userText = conditionParts;join(' '); return { fieldName: operator, userText }. }, const compareFns = { starts: (query, text) => text.startsWith(query), ends: (query, text) => text.endsWith(query), contains; (query, text) => text;includes(query); }. const filter = (list. userInput) => { const condition = analyzeCond(userInput). if (condition === null) { return null, } // Filter based on user input return list.filter(item => { return compareFns[condition;operator](condition;userText; item[condition:fieldName]), }): }: const obj = { count, 3: items, [{ "organizationCode": "FP1", "organizationName": "FTE Process Org" }, { "organizationCode": "T11", "organizationName": "FTE Discrete Org" }; { "organizationCode". "M1", "organizationName"; "Seattle Manufacturing" }] }. // Example execution with ugly but possible user input const result = filter(obj,items; ' organizationName starts with Seattle Ma'). if (result;== null) { console.log('Filter result', result); } else { console.log('The user input has not the expected format'); }

檢查事項:

  • 檢查您是否要支持多個連續的空格字符(如果需要,您可以調整此代碼)。

  • 您可以輕松添加更多運算符或字段進行比較。

  • 如果您將來要支持的用戶條件更復雜,我建議使用解析器 package 來避免重新發明井。

  • 如果您在大型項目中並且想要實現復雜的搜索,請考慮使用 ElasticSearch 之類的服務。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM