-1

I have an object called _test shaped in the below form where the first element is id and the second is name:

"_test": [
    {id:1, name:andy},{id:2, name:james}, {id:3, name:mike} 
]

I then have another field called key. the values that key takes on can equal values of id in the subs

key

I currently use

_test.flatMap( c => c.id).find(elem => elem == key) || null

How can I get this to return the name? I'm at a loss and having a major brain fart.

Barmar
  • 741,623
  • 53
  • 500
  • 612
ts4r
  • 21
  • 5
  • 2
    Arrays don't have keys. They have numeric indexes. You probably should be using an array of objects, not an array of arrays. – Scott Marcus Oct 25 '22 at 19:25
  • hi i made an error in wording. i am actually working nested objects. the object has ids and names, there are 3 nested objects within, if that makes sense! I have edited my question now – ts4r Oct 25 '22 at 19:25
  • 2
    For future reference, get familiar with [how to access and process objects, arrays, or JSON](/q/11922383/4642212), and what [objects](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Object_initializer) and [arrays](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/Array#array_literal_notation) look like in literal notation. Then [edit] and provide the literal form of your object. – Sebastian Simon Oct 25 '22 at 19:26
  • 1
    `flatMap()` is converting the array of objects into an array just containing the IDs. Don't do that. – Barmar Oct 25 '22 at 19:28
  • hi I made an edit after my edit! Sorry I'm still very new to js, and I wanted to say I really appreciate all the corrections, and notes on syntax – ts4r Oct 25 '22 at 19:29
  • [Duplicate](//google.com/search?q=site:stackoverflow.com+js+find+object+by+value+of+property) of [Find object by id in an array of JavaScript objects](/q/7364150/4642212). It’s `yourObject._test.find(({ id }) => id === key)?.name ?? null`. Note that `find` already returns `undefined`, when nothing is found; using `null` as an alternative doesn’t really make a huge difference. – Sebastian Simon Oct 25 '22 at 19:30

2 Answers2

0

You can find the name for a given id via:

const
  _test = [
    { id: 1, name: 'Andy'  },
    { id: 2, name: 'James' },
    { id: 3, name: 'Mike'  }
  ],
  key = 2,
  { name } = _test.find(({ id }) => id === key) ?? {};

console.log(name); // James
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
-1

actually is pretty easy, you just need to use find on your array, it takes a function as an argument.

pd: when doing ([id, name]) I'm destructuring the array, you can change that to:

names.find(entry => key === entry[0])

const names = [
  [1, 'andy'],
  [2, 'james'],
  [3, 'mike']
];
const key = 3;
const solution = names.find(([id, name]) => key === id)

console.log("solution => ", solution)
console.log("just the name => ",
  solution[1]);
Prince Hernandez
  • 3,623
  • 1
  • 10
  • 19