Filter JavaScript Object by value -
i have object array:
var result = [ { appaddress:"127.0.0.1", name:"appserver1", dbconnection:"" }, { appadress:"", name:"dbserver1", dbconnection:"server=.;database=master;integrated security=sspi" }];
now need name values (into array), appaddress isn't empty. tried array.filter() , $.map() none of these methods seems want.
this tried:
var appservers = $.map(result, function (val, key) { return (key == 'appaddress' && val.length > 0) ? key : null; });
and
var appservers = result.filter(function (entry) { return entry['displayname']; });
for filtering can use filter
, map
methods of array
. see below example.
var result = [{ appadress: "127.0.0.1", name: "appserver1", dbconnection: "" }, { appadress: "", name: "dbserver1", dbconnection: "server=.;database=master;integrated security=sspi" }]; // first solution var out = result.filter(function(obj) { return obj.appadress; }).map(function(obj) { return obj.name; }) // second solution var namesarr = []; result.foreach(function(obj) { if (obj.appadress) { namesarr.push(obj.name); } }); document.queryselector('#out').innerhtml = json.stringify(out, undefined, 4); document.queryselector('#out2').innerhtml = json.stringify(namesarr, undefined, 4);
first solution <pre id="out"></pre> <hr/> second solution <pre id="out2"></pre>
Comments
Post a Comment