-1

I have this array

var getDay: [
    { DayValue: '10D', DayDisplay: '10' },
    { DayValue: '20D', DayDisplay: '20' },
    { DayValue: '30D', DayDisplay: '30' }
      ]

Now there is another code as follows.

var b_day = getDayDetails('10D')

This will get 10D and check the corresponding DayDisplay value in getDay array.

I want the final value of b_day as '10'

Similarly, if var b_day = getDayDetails('20D'), i want the final value of b_day as '20'

can someone please let me know how to achieve this?

Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161
Rihana
  • 403
  • 2
  • 7
  • 14
  • This is literally one line of code. What have you tried? – Laoujin Jul 03 '17 at 18:17
  • 2
    Possible duplicate of [Get JavaScript object from array of objects by value or property](https://stackoverflow.com/questions/13964155/get-javascript-object-from-array-of-objects-by-value-or-property) – Daniel Beck Jul 03 '17 at 18:18

4 Answers4

2

Use a filter:

function getDayDetails (input) {
    if(getDay.length) {
        var v = getDay.filter(function(element) {
            return element.DayValue === input;
        });
        if(v.length) return v[0].DayDisplay;
        else return null;
    } else return null;
}
cst1992
  • 3,823
  • 1
  • 29
  • 40
1

You should be using _.find to achieve this

function getDayDetails(data){
    return _.find(getDay,{'DayValue':data});
}
function getDayDisplayDetails(data){
    return _.find(getDay,{'DayDisplay':data});
}

LIVE DEMO

Aravind
  • 40,391
  • 16
  • 91
  • 110
1

Simple:

function findDay(dayParam) {
    const day = getDay.find(day => day.DayValue == dayParam);
    return day && day.DayDisplay;
}
tiagodws
  • 1,345
  • 13
  • 20
0

If I understand your question correctly, there are a couple of ways this could be done. Probably the simplest (admittedly not the best) way would just be a FOR loop going through the array and checking the object's properties at each index until you hit upon the right one.

Something like this:

function getDayDetails (v) {
    for (var i in getDay) {
        if (getDay[i].DayValue === v) return getDay[i].DayDisplay;
    }
}

This could probably be tidied up a bit, but that seems to be the sort of thing you're after.

Sam Conran
  • 156
  • 1
  • 7