-3

I get an array of objects from the backend as this one, currently only three elements but in the future will be more.

[{"code":"lng.dropdown.home","text":"Inicio"},

{"code":"lng.dropdown.shop","text":"Tienda"},  

{"code":"lng.button.support","text":"Soporte"}]

What is the most efficient way in javascript to find an element in this array by code, and return the text associated? Can we use lambdas expresions here?

Phiter
  • 14,570
  • 14
  • 50
  • 84
fgonzalez
  • 3,787
  • 7
  • 45
  • 79

2 Answers2

0

When not using other libraries, I usually map then find the indexOf, as follows:

data[data.map(function(a){ return a.code }).indexOf("code I am trying to find")];

This returns the element of data at the index where code matches the code you're trying to find.

When I have lodash as a dependency, I usually just do this however:

_.find(data, {code:"code I am trying to find"})

(I think that's the proper syntax)

Edit:

Didn't realize you were already using JQuery, the answer using $.grep is probably best.

Nick Nasirpour
  • 268
  • 1
  • 8
0

you can use array filter to find the nested object(s) that matches your code property:

var arr =
[{"code":"lng.dropdown.home","text":"Inicio"},

{"code":"lng.dropdown.shop","text":"Tienda"},  

{"code":"lng.button.support","text":"Soporte"}];

var res = arr.filter(function(x){
return x.code == 'lng.dropdown.home'
})

console.log(res[0])

[].filter returns an array with the objects that return true inside the callback.

As far as efficiency is concerned for loop are proved to be faster but using higher order methods you earn abstraction .

maioman
  • 18,154
  • 4
  • 36
  • 42