I have two array of objects like following:
result = [{id:24, name:\"xyz\"}, {id:45,name:\"tze\"}]
moreDetails = [{id:
You can use a for
loop, in this case extending one of the arrays' elements is better than creating another array:
for (var i = 0; i < result.length; i++) {
result[i].name2 = moreDetails[i].name2;
}
http://jsfiddle.net/9uchU/
In case that target elements have different indices:
for (var i = 0; i < result.length; i++) {
var c = result[i],
// filtering the second array based on the `id`
// of the current element
m = moreDetails.filter(function(elem) {
return elem.id === c.id;
})[0];
c.name2 = m ? m.name2 : 'not defined';
}
Edit: Based on your last edit, as @Blender mentions, you can also use jQuery $.extend()
utility function:
$.extend(result, moreDetails);
<html>
<head><title></title>
<script src="http://code.jquery.com/jquery-1.10.0.min.js" ></script>
</head>
<body>
<script>
function findElement(arr, propName, propValue) {
for (var i=0; i < arr.length; i++){
if (arr[i][propName] == propValue){
return arr[i];
}
}
}
var result = [{id:24, name:"xyz"}, {id:45,name:"tze"}];
var moreDetails= [{id:24, name2:"hyi"}, {id:45, name2:"tikw"}];
var mergedResult = result;
for (var i = 0; i<result.length;i++ ) {
//mergedResult[i].name2 = findElement(moreDetails, "id", result[i].id).name2
$.extend(mergedResult[i],findElement(moreDetails, "id", result[i].id));
}
mergedResult;
</script>
</body>
</html>