How to get the next attribute of an object array?

Asked

Viewed 117 times

0

Good night, guys, so I’m locked in a code here. I have an array of objects, and I will receive an input name, which is found in one of the "display" objects of the array below, for example "Márcio Magalhães".

After that, I need to look for the display and the name of the object following this, for example in this case would be "Alex Jones" and "F1207158".

const list_members = {
  "members": [{
    "value": "646d70b7f6974459b188174aa8a564fe",
    "type": "User",
    "display": "Márcio Magalhẽs",
    "name": "B133232",
    "$ref": "examplefortest.com"
  }, 
  {
    "value": "646d70b7f6974459b188174aa8a564fe",
    "type": "User",
    "display": "Alex Jones",
    "name": "F1207158",
    "$ref": "examplefortest.com"
  }, 
  {
    "value": "646d70b7f6974459b188174aa8a564fe",
    "type": "User",
    "display": "Bibiana Fonseca",
    "name": "G123454",
    "$ref": "examplefortest.com"
  }]
}

My question is how to take this data, I tried to start implementing something like this but I could not progress

const { members: [display, name]} = lista_membros.find(({members})) => members.includes("Márcio Magalhães"));

1 answer

0


You can use the .findIndex to search the array for the index of that name/display you have. Then add +1 and you have the next.

Note that when you reach the end of this array (when there is no next one) the function will return undefined.

const list_members = {
  "members": [{
      "value": "646d70b7f6974459b188174aa8a564fe",
      "type": "User",
      "display": "Márcio Magalhẽs",
      "name": "B133232",
      "$ref": "examplefortest.com"
    },
    {
      "value": "646d70b7f6974459b188174aa8a564fe",
      "type": "User",
      "display": "Alex Jones",
      "name": "F1207158",
      "$ref": "examplefortest.com"
    },
    {
      "value": "646d70b7f6974459b188174aa8a564fe",
      "type": "User",
      "display": "Bibiana Fonseca",
      "name": "G123454",
      "$ref": "examplefortest.com"
    }
  ]
};

function getUserAfter(display, arr) {
  const startIndex = arr.findIndex(obj => obj.display === display);
  return arr[startIndex + 1];
}

console.log(getUserAfter("Márcio Magalhẽs", list_members.members));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.