Home > Enterprise >  Search user in object and return key name if found [closed]
Search user in object and return key name if found [closed]

Time:09-30

I'm new to Vue and Javascript and for my work I need to find the specific room certain user connected to. I'm still learning so i'm not very good with ES6 or javascript functions.

I need to search userId in rooms and return the name of the key ('pre', 'mid', 'post') if the id is found, if not then return null

const userId = "321b66bb-b44f-4859-994a-a339e604df62";

const rooms = {
    "pre": [
        {   
            "id": "321b66bb-b44f-4859-994a-a339e604df62", 
            "name": "George", 
            "age": "27", 
            "color": "#0B8043",
            "callIndex": 960433
        },
        {   
            "id": "1111111-11111-1111-1111-111111111111", 
            "name": "John", 
            "age": "30", 
            "color": "#0B8043",
            "callIndex": 4444444
        },
    ],
    "mid": [
        {   
            "id": "1111111-11111-1111-1111-111111111112", 
            "name": "John2", 
            "age": "30", 
            "color": "#0B8043",
            "callIndex": 4444444
        },
    ],
    "post": []
};

CodePudding user response:

You can iterate through each key and then compare the id with passed userId and return then key name.

const userId = "321b66bb-b44f-4859-994a-a339e604df62",
      rooms = { "pre": [ { "id": "321b66bb-b44f-4859-994a-a339e604df62", "name": "George", "age": "27", "color": "#0B8043", "callIndex": 960433 }, { "id": "1111111-11111-1111-1111-111111111111", "name": "John", "age": "30", "color": "#0B8043", "callIndex": 4444444 }, ], "mid": [ { "id": "1111111-11111-1111-1111-111111111112", "name": "John2", "age": "30", "color": "#0B8043", "callIndex": 4444444 }, ], "post": [] },
      result = Object.keys(rooms).find(k => rooms[k].some(({id}) => id === userId)) || null;
console.log(result);

CodePudding user response:

Easy task

const userId = "321b66bb-b44f-4859-994a-a339e604df62";

const rooms = {
  "pre": [{
      "id": "321b66bb-b44f-4859-994a-a339e604df62",
      "name": "George",
      "age": "27",
      "color": "#0B8043",
      "callIndex": 960433
    },
    {
      "id": "1111111-11111-1111-1111-111111111111",
      "name": "John",
      "age": "30",
      "color": "#0B8043",
      "callIndex": 4444444
    },
  ],
  "mid": [{
    "id": "1111111-11111-1111-1111-111111111112",
    "name": "John2",
    "age": "30",
    "color": "#0B8043",
    "callIndex": 4444444
  }, ],
  "post": []
};

function search(id) {
  for (let key in rooms) {
    // key is pre, mid or post
    for (let item of rooms[key]) {
      // item is an object containing id
      if (item.id === id) return key
    }
  }
  return null
}

console.log(search(userId))

  • Related