How i can get data from another object?

Plunker I have two structures - ingredients and recipes

[{
    "id":"1",
    "name": "Cucumber"
 },
 ..
]

and

 [{
     "id":"1",
     "name": "Salad1",
     "recipein":[1, 3, 5]
  }, {
      ...
  }
 ]

and i want to show names of ingredients in each salad by press a button. I filtered object to get ID of object, then i try to get a array of ingredients

getSalad(param:number) {
    this.saladId = this.recipe.filter(rec => {
        return rec.id.includes(param);
    })  

    this.getNameOfIngredients(this.saladId)
 }

 getNameOfIngredients(saladArray:any) {
     var ingredientsId = saladArray.map(function(num) {
     return num.recipein;
 });

i getting array [1,2,4] now i want to show all names of ingredients from this.ingredients with this array of id's. How can i do this?

Plunker

3 answers

  • answered 2018-04-17 06:15 KE LIU

    let _ingredients = []
    this.ingredients.foreach((ingr)=>{
        if(this.ingreIDArry.indexof(ingr.id) > -1){
            _ingredients.push(ingr.name)
        }
    })
    return _ingredients
    

    is this what you want?

  • answered 2018-04-17 06:20 Sreekanth

    if you can flatten the array, it would be very straightforward for us to do lookups.

    Here is what you could do.

    const salads = [{
      "id": "1",
      "name": "Salad1",
      "recipein": [1, 3, 5]
    }];
    
    const ingredients = [{
        "id": "1",
        "name": "Cucumber"
      },
      {
        "id": "2",
        "name": "Cucumber2"
      },
      {
        "id": "3",
        "name": "Cucumber3"
      },
      {
        "id": "4",
        "name": "Cucumber4"
      },
      {
        "id": "5",
        "name": "Cucumber5"
      }
    ];
    
    const flattenIngredients = (() => {
      const output = {};
      ingredients.forEach((ingredient) => {
        output[ingredient.id] = ingredient;
      });
      return output;
    })();
    
    const getSalad = (saladId) => {
      const filteredSalad = salads.filter((salad) => {
        return saladId == salad.id;
      });
      if (filteredSalad.length > 0) {
        const salad = filteredSalad[0];
        return salad.recipein.map((receip) => flattenIngredients[receip].name);
      }
    }
    
    console.log(getSalad(1));

  • answered 2018-04-17 06:27 Kuba

    I made updates in your plunker. I think thats what are you looking for: Plunker

      getSalad(param:number) {
    
       this.saladId = this.recipe.filter(rec => +rec.id === param )[0];
        if(!this.saladId){
          this.currentSalad = "Salad not found";
          return;
        }
       this.currentSalad = this.getNameOfIngredients(this.saladId)
    
      }
    
      getNameOfIngredients(saladArray:any) {
        return this.ingredients.filter( ing => {
          return saladArray.recipein.indexOf(+ing.id) !== -1;
      });