array element update
by Nivaldo
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.12.0/lodash.min.js"></script>
JavaScript
// replacing elements in arr1 with same-id elements in array 2
// e.g. the id here is 'code'
// see http://stackoverflow.com/questions/27641731/is-there-a-function-in-lodash-to-replace-matched-item
var allEntitlements = [
{code: 'pi', groups: ['db'], checked: false},
{code: 'pa', groups: ['db'], checked: false},
{code: 'pb', groups: ['db','hb'], checked: false}
];
/*
the object structures in the selected array will replace the
object structures in the all array; keep them same if desired
see https://davidwalsh.name/javascript-clone-array for details
*/
var selEntitlements = [
{code: 'pi', groups: ['db'], checked: true},
{code: 'pb', groups: ['db','hb'], checked: true}
];
function transform(arr1,arr2) {
// we first clone the passed-in arrays to avoid changing them
var _arr1 = arr1.slice(0),_arr2 = arr2.slice(0);
for (ct=0; ct<_arr2.length; ct++) {
var index = _.findIndex(_arr1, _.pick(_arr2[ct], 'code'));
if( index !== -1) {
_arr1.splice(index, 1, _arr2[ct]);
} else {
_arr1.push(_arr2[ct]);
}
}
return _arr1;
}
var newArray = transform(allEntitlements,selEntitlements);
console.log(allEntitlements);
console.log(selEntitlements);
console.log(newArray);