To be efficient, you could store the locations of each item and then use that to reference the name:
var things = [
{
id: "12345",
name: "Bryan"
},
{
id: "55555",
name: "Justin"
}
], reference = things.map(function(a){ return a.id });;
function replace (id, name, ar, ref) { ref.indexOf(id)>-1&&(ar[ref.indexOf(id)]['name']=name); }
replace("55555", "Phil", things, reference);
In this, you will only need to loop one time. Then all the information is stored in the reference
variable. reference
stores where the id
is, which we use to avoid looping. I'm not sure what the compiler is doing and whether it loops or not but this just feels more efficient.
.indexOf isn't completely supported so you can use a PollyFill
Add this code to the top of the JavaScript file:
[].indexOf||(Array.prototype.indexOf=function(a,b,c){for(c=this.length,b=(c+~~b)%c;b<c&&(!(b in this)||this[b]!==a);b++);return b^c?b:-1;})
and
Array.prototype.map||(Array.prototype.map=function(r,t){var n,o,e;if(null==this)throw new TypeError(" this is null or not defined");var i=Object(this),a=i.length>>>0;if("function"!=typeof r)throw new TypeError(r+" is not a function");for(arguments.length>1&&(n=t),o=new Array(a),e=0;a>e;){var p,f;e in i&&(p=i[e],f=r.call(n,p,e,i),o[e]=f),e++}return o});
along with:
Array.prototype.forEach||(Array.prototype.forEach=function(r,t){var o,n;if(null==this)throw new TypeError(" this is null or not defined");var e=Object(this),i=e.length>>>0;if("function"!=typeof r)throw new TypeError(r+" is not a function");for(arguments.length>1&&(o=t),n=0;i>n;){var a;n in e&&(a=e[n],r.call(o,a,n,e)),n++}});
Retrieved from: here, here, and here
Note: While IE 8 and below don't support indexOf
practically every other browser does.