LorneCash LorneCash - 3 months ago 13
Javascript Question

Get Item from Array with Property equal to Value

This questions is for my LightSwitch project but I'm not sure that's renavent. I've never done javascript or jquery before and i'm pretty sure this will have nothing to do with LightSwitch and everything to do with the latter.

The following code works perfectly setting test equal to 4 in my case:

myapp.BrowseTreeNodes.TreeNodes_render = function (element, contentItem) {
var screen = contentItem.screen;
var result = screen.MyArray.data[0];
var test = result.Id;

What I need to do is instead of setting result to the first item in the array I need to set result to the item with a specific Id, for this example let's say 4.

Here's what i've tried:

var result = $.grep(screen.MyArray.data, function (e) { return e.Id === 4; })[0];
var result = screen.MyArray.data.filter(function (v) { return v.Id === 4; })[0];
var result = screen.MyArray.data.find(x => x.Id === 4)[0];

Thank you in advance.


your problem may be the === , === checks for type as well, so "4" === 4 is false while "4" == 4 is true, check if your id property is stored as a string or an integer...