Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript get a value based upon another in array of objects

Tags:

javascript

i am trying to return a value from an array of objects in javascript, the first object in the array is;

 dict=[{index:"1",caption:"AAAffterA",blurb:"stuff to write here asieh 1flsidg"}]

how can i return the "blurb" value(B) if i have the "caption" value(A)? i have managed to do it the looong way but i am sure there is an easier way ?

A = "AAAffterA"
var result = dict.map(function(a) {return a.caption;});
key = jQuery.inArray(A,result)
B = dict[key].blurb
like image 785
Anton Avatar asked Aug 18 '26 23:08

Anton


2 Answers

Just one function to call.

var dict = [{ index: "1", caption: "AAAffterA", blurb: "stuff to write here asieh 1flsidg" }],
    a = "AAAffterA",
    b = dict.reduce(function (res, el) {
        return el.caption === a ? el.blurb : res;
    }, undefined);
alert(b);

Here a solution for multiple occurence:

var dict = [{ index: "1", caption: "AAAffterA", blurb: "stuff to write here asieh 1flsidg" }, { index: "2", caption: "AAAffterA", blurb: "index 2 stuff to write here asieh 1flsidg" }],
    a = "AAAffterA",
    b = dict.reduce(function (res, el) {
        el.caption === a && res.push(el.blurb);
        return res;
    }, []);
alert(JSON.stringify(b));
like image 107
Nina Scholz Avatar answered Aug 20 '26 14:08

Nina Scholz


You almost had it.

Instead of returning the caption and then looking it up in the dict again just return the blurb back from the map. It will return something like this ["stuff to write here asieh 1flsidg"]

Now, you can reduce the last two lines by just extracting the first result directly from the array that was returned. The first element of the newly created array is the string you want to return. ["stuff to write here asieh 1flsidg"][0] is just stuff to write here asieh 1flsidg

> dict=[{index:"1",caption:"AAAffterA",blurb:"stuff to write here asieh 1flsidg"}]
[ { index: '1',
    caption: 'AAAffterA',
    blurb: 'stuff to write here asieh 1flsidg' } ]
> dict.map ( function(a) { if (a.caption == "AAAffterA") return a.blurb } )
[ 'stuff to write here asieh 1flsidg' ]

Since the array may have multiple values, including nil, filter through this array to return non empty results and return the first non empty result using [0].

>[ ,,,'stuff to write here asieh 1flsidg' ,,,].filter( function(a) {    
   if (a!=null) return a 
  } ) [0]
    'stuff to write here asieh 1flsidg'

Combine into one final function

> dict.map ( function(a) 
 { if (a.caption == "AAAffterA") 
     return a.blurb } 
 ).filter( function(a) { 
    if (a!=null) return a } 
  ) [0]
'stuff to write here asieh 1flsidg'
like image 23
aarti Avatar answered Aug 20 '26 12:08

aarti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!