skip to Main Content

I have an array of the following type retrieved from an API

{
 strIngredient1: "Chicken"
 strIngredient2: "Onion"
 strIngredient3: "Tomatoes"
 strIngredient4: ""
 strIngredient5: ""
 strIngredient6: ""
 strMeasure1: 1lb
 strMeasure2: 2
 strMeasure3: 3
 strMeasure4: ""
 strMeasure5: ""
 strMeasure6: ""
}

And I need to filter out the ingredients and measures which are not null and combine those in the format of ingredients-measure (eg. Chicken – 1lb).

I tried using the filter and map on the object as below

const validIngredients = Object.keys(singleRecipe)
    .filter((item) => {
      if (item.startsWith("strIngredient") && singleRecipe[item] !== "") {
        return item;
      }
      if (item.startsWith("strMeasure") && singleRecipe[item] !== "") {
        return item;
      }
    })
    .map((key) => singleRecipe[key]);

and was able to retrieve the values which are not null in the below format in the console
(6)["Chicken","Onion","Tomatoes","1lb","2","3"].
I’m not able to figure out how to concatenate the values. Any suggestions for retrieving these values differently?

2

Answers


  1. Map will return an array, you just mapped from key to values.

    You should remove the map function, and in new line will combine the ingredient to the measurement.

    const res = {}
    for (let i=0, j=validIngredients.length / 2; i< validIngredients.length / 2; ++i, ++j){
        res[validIngredients[i]] = validIngredients[j]]
    }
    
    Login or Signup to reply.
  2. To concatenate the ingredients and measures in the desired format, you can modify your code slightly. Instead of filtering and mapping separately, you can perform both operations within a single reduce function. Here’s how you can do it:

    javascript
    const singleRecipe = {
      strIngredient1: "Chicken",
      strIngredient2: "Onion",
      strIngredient3: "Tomatoes",
      strIngredient4: "",
      strIngredient5: "",
      strIngredient6: "",
      strMeasure1: "1lb",
      strMeasure2: "2",
      strMeasure3: "3",
      strMeasure4: "",
      strMeasure5: "",
      strMeasure6: "",
    };
    
    const validIngredients = Object.keys(singleRecipe).reduce((result, key) => {
      if (key.startsWith("strIngredient") && singleRecipe[key] !== "") {
        const ingredientIndex = key.replace("strIngredient", "");
        const measureKey = `strMeasure${ingredientIndex}`;
        if (singleRecipe[measureKey] !== "") {
          result.push(`${singleRecipe[key]} - ${singleRecipe[measureKey]}`);
        } else {
          result.push(singleRecipe[key]);
        }
      }
      return result;
    }, []);
    
    console.log(validIngredients);
    
    
    Output:
    ["Chicken - 1lb", "Onion - 2", "Tomatoes - 3"]
    

    In this code, we use reduce to iterate over the keys of the singleRecipe object. For each key that starts with "strIngredient" and has a non-empty value, we check if there’s a corresponding measure with a non-empty value. If so, we concatenate the ingredient and measure with a hyphen and push it to the result array. Otherwise, we only push the ingredient value to the array. Finally, we get the desired format for valid ingredients and measures.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search