jquery - Filtering Javascript object array -
i trying new array object based on 2 of them.
log1 = {1:"london",2:"new york",4:"berlin"}; log2 = [{id:1, location:"eu"},{id:2, location:"us"},{id:18, location:"asia"}];
i want make sure log1 keys exist in log2 and, if not, want delete it. be:
result = {1:"london",2:"new york"};
i couldn't filter take 1 object. there way filter based on 2 object arrays? there neat way ?
if using recent version of js array.map()
, array.filter()
, object.keys()
try following more functional approach:
var log1 = { 1: "london", 2: "new york", 4: "berlin" }; var log2 = [ {id: 1, location: "eu"}, {id: 2, location: "us"}, {id: 18, location: "asia"} ]; var ids = log2.map(function(obj) { return obj.id; }).map(string); object.keys(log1).filter(function(key) { return ids.indexof(key) === -1; }).foreach(function(k) { delete log1[k]; }); console.log(log1);
should yield:
{ '1': 'london', '2': 'new york' }
example: http://repl.it/rnf/2
hope helps :)
edit
otherwise, browser compatibility , more consider lodash or underscore suggested other posters. or use polyfill!
mdn provides polyfills @ bottom of each of following pages older environments (in case require compatibility):
Comments
Post a Comment