Home > front end >  How do i filter a value of key in an object based on matching value?
How do i filter a value of key in an object based on matching value?

Time:04-30

I have an object that contains objects. How do i filter out the value of "title" based on whether the id is matching?

{
    "0": {
        "id": 1912,
        "title": "Fiction",
    },
    "1": {
        "id": 1957,
        "title": "Non-Fiction",
    },
    "2": {
        "id": 1958,
        "title": "Literature",
    },
}

For example, if the const id=1958, then the output: Literature

Output:

Literature

CodePudding user response:

You can try this:

let data = {
    "0": {
        "id": 1912,
        "title": "Fiction",
    },
    "1": {
        "id": 1957,
        "title": "Non-Fiction",
    },
    "2": {
        "id": 1958,
        "title": "Literature",
    },
};

let getTitle = (obj, id)=>{
 return Object.values(obj).filter(x=>x.id===id)?.[0]?.title
};

console.log(getTitle(data,1958))

You can also use find instead of filter.

Without optional chaining as per OPs comment:

   let data = {
        "0": {
            "id": 1912,
            "title": "Fiction",
        },
        "1": {
            "id": 1957,
            "title": "Non-Fiction",
        },
        "2": {
            "id": 1958,
            "title": "Literature",
        },
    };

    let getTitle = (obj, id)=>{
      let element = Object.values(obj).find(x=>x.id===id);
      return element ? element.title : "";
    };

    console.log(getTitle(data,1958))

  • Related