根据数组对象替换句子中的单词

时间:2019-06-22 18:04:26

标签: javascript arrays object

我有一个从API获取的成分对象。我想用其缩写替换每个成分中的单位。我正在尝试使用名为units的对象并使用要在数组中替换的值来实现此目的,但我什至无法使其起作用。

我已经尝试了许多不同的方法,这是我最近的尝试:

parseIngredient() {
    const ingredients = [
      "1 fresh ham, about 18 pounds, prepared by your butcher (See Step 1)",
      "7 cloves garlic, minced",
      "1 tablespoon caraway seeds, crushed",
      "4 teaspoons salt",
      "Freshly ground pepper to taste",
      "1 teaspoon olive oil",
      "1 medium onion, peeled and chopped",
      "3 cups sourdough rye bread, cut into 1/2-inch cubes",
      "1 1/4 cups coarsely chopped pitted prunes",
      "1 1/4 cups coarsely chopped dried apricots",
      "1 large tart apple, peeled, cored and cut into 1/2-inch cubes",
      "2 teaspoons chopped fresh rosemary",
      "1 egg, lightly beaten",
      "1 cup chicken broth, homemade or low-sodium canned"
    ];

    const units = {
      tbsp: ['tablespoons', 'tablespoon', 'tbsps', 'tbsp'],
      tsp: ['teaspoons', 'teaspoon', 'tsps', 'tsp'],
      cup: ['cups', 'cup'],
      oz: ['ounces', 'ounce'],
      pt: ['pints', 'pint', 'pt'],
      gal: ['gallons', 'gallon', 'gals', 'gal'],
      pound: ['pounds', 'pound', 'lbs', 'lb'],
      qt: ['quarts', 'quart', 'qts', 'qt'],
      l: ['liters', 'liter', 'l'],
      ml: ['mililiters', 'mililiter', 'mls', 'ml'],
      cl: ['centiliters', 'centiliter', 'cls', 'cl'],
      kg: ['kilograms', 'kilogram', 'kgs', 'kg'],
      g: ['grams', 'gram', 'gs', 'g'],
      mg: ['miligrams', 'miligram', 'mgs', 'mg'],
      inch: ['inches', 'inch', 'in']
    };

    const changedIngredients = ingredients.map(el => {
        let ing = el.toLowerCase();
        const keys = Object.keys(units);
        const values = Object.values(units);

        values.forEach((value, i) => {
            for (let j; j <= value.length; j++) {
                ing = ing.replace(value[j], keys[i]);
            }
        });
    });
}

例如,我希望"4 teaspoons salt"的输出为"4 tbsp salt"

2 个答案:

答案 0 :(得分:0)

要维护数据结构,您首先可以从units对象生成一个成对数组,其中每个对都由替换和用于该替换的正则表达式组成。为了生成该对数组,我们可以将units对象上的Object.entries()Array.map()结合使用。请注意,不区分大小写功能已添加到带有标志i的正则表达式中。同样,在创建正则表达式时,我们使用word boundaries (\b)来匹配整个单词而不是其他单词的一部分(例如in中的minced)。可以在下一个逻辑中看到对此的总结:

const replacements = Object.entries(units).map(([k, v]) =>
{
    v = v.map(s => `\\b${s}\\b`).join("|");
    return [k, new RegExp(v, "i")];
});

最后,您可以像已经做的那样.map() 成分,将各自的替换项应用于数组的每个元素。

const changedIngredients = ingredients.map(el =>
{
    replacements.forEach(([unit, regexp]) => el = el.replace(regexp, unit));        
    return el;
});

完整示例:

const ingredients = [
  "1 fresh ham, about 18 pounds, prepared by your butcher (See Step 1)",
  "7 cloves garlic, minced",
  "1 tablespoon caraway seeds, crushed",
  "4 teaspoons salt",
  "Freshly ground pepper to taste",
  "1 teaspoon olive oil",
  "1 medium onion, peeled and chopped",
  "3 cups sourdough rye bread, cut into 1/2-inch cubes",
  "1 1/4 cups coarsely chopped pitted prunes",
  "1 1/4 cups coarsely chopped dried apricots",
  "1 large tart apple, peeled, cored and cut into 1/2-inch cubes",
  "2 teaspoons chopped fresh rosemary",
  "1 egg, lightly beaten",
  "1 cup chicken broth, homemade or low-sodium canned"
];

const units = {
  tbsp: ['tablespoons', 'tablespoon', 'tbsps', 'tbsp'],
  tsp: ['teaspoons', 'teaspoon', 'tsps', 'tsp'],
  cup: ['cups', 'cup'],
  oz: ['ounces', 'ounce'],
  pt: ['pints', 'pint', 'pt'],
  gal: ['gallons', 'gallon', 'gals', 'gal'],
  pound: ['pounds', 'pound', 'lbs', 'lb'],
  qt: ['quarts', 'quart', 'qts', 'qt'],
  l: ['liters', 'liter', 'l'],
  ml: ['mililiters', 'mililiter', 'mls', 'ml'],
  cl: ['centiliters', 'centiliter', 'cls', 'cl'],
  kg: ['kilograms', 'kilogram', 'kgs', 'kg'],
  g: ['grams', 'gram', 'gs', 'g'],
  mg: ['miligrams', 'miligram', 'mgs', 'mg'],
  inch: ['inches', 'inch', 'in']
};

const replacements = Object.entries(units).map(([k, v]) =>
{
    v = v.map(s => `\\b${s}\\b`).join("|");
    return [k, new RegExp(v, "i")];
});

const changedIngredients = ingredients.map(el =>
{
    replacements.forEach(([unit, regexp]) => el = el.replace(regexp, unit));        
    return el;
});

console.log(changedIngredients);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

答案 1 :(得分:0)

这是所需输出的代码

// Polyfill of Contains method On String
if(!('contains' in String.prototype)) {
       String.prototype.contains = function(str, startIndex) {
                return -1 !== String.prototype.indexOf.call(this, str, startIndex);
       };
 }

function parseIngredient() {
  const ingredients = [
  "1 fresh ham, about 18 pounds, prepared by your butcher (See Step1)",
  "7 cloves garlic, minced",
  "1 tablespoon caraway seeds, crushed",
  "4 teaspoons salt",
  "Freshly ground pepper to taste",
  "1 teaspoon olive oil",
  "1 medium onion, peeled and chopped",
  "3 cups sourdough rye bread, cut into 1/2-inch cubes",
  "1 1/4 cups coarsely chopped pitted prunes",
  "1 1/4 cups coarsely chopped dried apricots",
  "1 large tart apple, peeled, cored and cut into 1/2-inch cubes",
  "2 teaspoons chopped fresh rosemary",
  "1 egg, lightly beaten",
  "1 cup chicken broth, homemade or low-sodium canned"
]
const units = {
  tbsp: ['tablespoons', 'tablespoon', 'tbsps', 'tbsp'],
  tsp: ['teaspoons', 'teaspoon', 'tsps', 'tsp'],
  cup: ['cups', 'cup'],
  oz: ['ounces', 'ounce'],
  pt: ['pints', 'pint', 'pt'],
  gal: ['gallons', 'gallon', 'gals', 'gal'],
  pound: ['pounds', 'pound', 'lbs', 'lb'],
  qt: ['quarts', 'quart', 'qts', 'qt'],
  l: ['liters', 'liter', 'l'],
  ml: ['mililiters', 'mililiter', 'mls', 'ml'],
  cl: ['centiliters', 'centiliter', 'cls', 'cl'],
  kg: ['kilograms', 'kilogram', 'kgs', 'kg'],
  g: ['grams', 'gram', 'gs', 'g'],
  mg: ['miligrams', 'miligram', 'mgs', 'mg'],
  inch: ['inches', 'inch', 'in']
};
const changedIngredients = ingredients.map(el => {
  let ing = el.toLowerCase();
  let shortHandedOutput=[];
  for(var prop in units){
     units[prop].map(u => {
      if(ing.contains(u)){ // Finds if the entry is in units
        ing = ing.replace(u,prop);
      }
   })
  }
  return ing;
});
}
// Execute Function
parseIngredient();