Search code examples
javascriptjsonobject

Getting the object using one of it's property's values


I have a json that, lets say it looks something like this:

[
  {
  "name":"Foo"
  "nickname":"Lorem Ipsum"
  },
  {
  "name":"Bar"
  "nickname":"Dolor Sit"
  }
]

Now, i want to find the nickname of something using the value of nickname to find it. Is there a way to do this in JavaScript? If so, how?


Solution

  • Given the input should be corrected in a way pointed out in my comment to be a proper and correct JSON, this function will serve the purpose.

    function findByName(name) {
      const i = [{
          "name": "Foo",
          "nickname": "Lorem Ipsum"
        },
        {
          "name": "Bar",
          "nickname": "Dolor Sit"
        }
      ]
      
      return i.find(e => e.name === name).nickname;
    }
    
    const res = findByName("Foo"); // ==> "Lorem Ipsum"
    console.log(res);