Home > Mobile >  Getting object data with key value in JavaScript
Getting object data with key value in JavaScript

Time:11-18

I have an object like this:

{
  "idMeal": "52795",
  "strMeal": "Chicken Handi",
  "strDrinkAlternate": null,
  "strCategory": "Chicken",
  "strArea": "Indian"
}

I am trying to get the value of other items(i.e. strMeal and strCategory) using the value of "idMeal". How can I do that?

CodePudding user response:

As far as i understood you want to filter an list of food objects, just put them in an array and filter like this:

[obj1, obj2, obj3].filter(o => o.idMeal="52795")

CodePudding user response:

First you should have stated what you tried. Then, you can use a simple condition:

let cat;
let area;
if (obj.idMeal === myValue) {
    cat = obj.strCategory;
    area = obj.strArea;
}

There are way more ways of doing this. Take a look at .map(), .filter() but those are for arrays.

CodePudding user response:

The easiest way to achieve this is to filter the data based on the key-value pair and then reduced the requested fields into a new object.

const mealData = [{
  "idMeal": "52795",
  "strMeal": "Chicken Handi",
  "strDrinkAlternate": null,
  "strCategory": "Chicken",
  "strArea": "Indian",
}];

const filterAndMap = (data, key, value, fields) =>
  data
    .filter((record) => record[key] === value)
    .map(record => fields.reduce((acc, field) =>
      ({ ...acc, [field]: record[field] }), {}));

const result = filterAndMap(mealData, 'idMeal', '52795', ['strMeal', 'strCategory']);

console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Alternatively, you could pass a filter function and a mapper function:

const mealData = [{
  "idMeal": "52795",
  "strMeal": "Chicken Handi",
  "strDrinkAlternate": null,
  "strCategory": "Chicken",
  "strArea": "Indian",
}];

const filterAndMap = (data, filterFn, mapperFn) =>
  data.filter(filterFn).map(mapperFn);

const result = filterAndMap(
  mealData,
  ({ idMeal }) => idMeal === '52795',
  ({ strMeal, strCategory }) => ({ strMeal, strCategory }));

console.log(result);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

In the example above, we can remove the filterAndMap function and just chain filter and map directly.

Show code snippet

const mealData = [{
  "idMeal": "52795",
  "strMeal": "Chicken Handi",
  "strDrinkAlternate": null,
  "strCategory": "Chicken",
  "strArea": "Indian",
}];

const result = mealData
  .filter(({ idMeal }) => idMeal === '52795')
  .map(({ strMeal, strCategory }) => ({ strMeal, strCategory }));

console.log(result);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related