如何从另一个对象获取数据



Plunker我有两种结构 - 成分和食谱

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

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

我想通过按下按钮显示每个沙拉中的成分名称。我过滤了对象以获取对象的ID,然后尝试获取一系列成分

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;
 });

我得到数组 [1,2,4] 现在我想显示 this.ingredients 的所有成分名称与这个数组的 id 的。 我该怎么做?

普伦克

我在你的 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;
  });
let _ingredients = []
this.ingredients.foreach((ingr)=>{
    if(this.ingreIDArry.indexof(ingr.id) > -1){
        _ingredients.push(ingr.name)
    }
})
return _ingredients

这是你想要的吗?

如果你能扁平化数组,那么我们进行查找将非常简单。

这是你可以做的。

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));

最新更新