Search code examples
javascriptvue.jsecmascript-6ecmascript-5

Javascript Object get object by property


I have an object of 2 users that looks like the following. The Object will only ever contain 2 users.

{
   "71":{
      "avatarURL":"__vue_devtool_undefined__",
      "createdAt":"2018-10-13T16:05:19Z",
      "customData":"__vue_devtool_undefined__",
      "id":"71",
      "name":"Angeline Fadel",
      "updatedAt":"2018-10-13T16:05:19Z",
      "presenceStore":{
         "71":"online"
      }
   },
   "199":{
      "avatarURL":"__vue_devtool_undefined__",
      "createdAt":"2018-10-13T16:06:13Z",
      "customData":"__vue_devtool_undefined__",
      "id":"199",
      "name":"Rodrigo Schuster",
      "updatedAt":"2018-10-13T16:06:13Z",
      "presenceStore":{
         "71":"online"
      }
   }
}

Let's say my user ID is 199, how to I get the name of the other user without knowing it's ID?


Solution

  • With Object.keys, you can get an array of keys:

    const users = { 199: {...}, 71: {...} };
    const ids = Object.keys(users); // -> ['199', '71']
    

    Knowing that the array will only contain two items and the "other" key, you might use Array.prototype.find to get the other item:

    const myId = '199';
    const targetId = ids.find(id => id !== myId); // -> '71'
    

    Remember that object keys are always strings, so you may want to tweak the filtering and operations on IDs in a way that they are treated as (or coerced into) numbers.