-2

I have an huge array of object and need to find the name of object by key, how can I do that with the optimized way.

const key = 2;
const arr = [ {id: 1, text: '1111'},  {id: 2, text: '2222'}, {id: 3, text: '333'},]

I need to return only the text '2222' The original array have an 154 object thats why I need the most optimized way.

arr.forEach((obj) => {
    Object.keys(obj).forEach((key) => {
        console.log("key : " + key + " - value : " + obj[key]);
  });
});
Avi
  • 1,049
  • 1
  • 5
  • 16
  • 4
    have you try [Array.prototype.find()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)? – Layhout Jan 17 '23 at 08:36
  • Is it possible for you to store the data in an object instead? eg `{ 1: { text: '1111' }, 2: { text: '2222' }, ... }`. Then you could access it with `yourObject[key]`. That's the only way to make it efficient afaik – A_A Jan 17 '23 at 08:37
  • There is a search feature at the top of the page which can be used to find answers to common questions like this one. [Example Search Results](https://stackoverflow.com/search?q=%5Bjavascript%5D+array+find+object) – Yogi Jan 17 '23 at 08:57

2 Answers2

0

JavaScript has great array methods to do these kind of things. In your case I would use array.find to achieve what you're after. You can read more about it here

const key = 2;
const arr = [ {id: 1, text: '1111'},  {id: 2, text: '2222'}...]

const result = arr.find((item) => item.id === key).text;
console.log(result) // will print '2222'
Avi
  • 1,049
  • 1
  • 5
  • 16
-1

You can do it using forEach or for loop

In term of optimisation for loop is the fastest one

var key = 2;
const arr = [ {id: 1, text: '1111'},  {id: 2, text: '2222'}, {id: 3, text: '333'},]

arr.forEach((obj) => {
      if (obj.id == key) {
        console.log(obj.text);
      }
});


for (let i = 0; i < arr.length; i++) {
     if (arr[i].id == key) {
        console.log(arr[i].text)  
     }        
}
SelVazi
  • 10,028
  • 2
  • 13
  • 29