Lodash.js – defaults() function
A simple Lodash.js example of the defaults() function, we can add new keys and their values, but without overwriting old keys and values of the destination object.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<meta name="description" content="Tizen example"/>
<title>Tizen lodash.js example</title>
<script src="js/lodash.min.js"></script>
</head>
<body>
<div id="first">
</div>
<br>
<div id="second">
</div>
<script>
var firstDiv = document.getElementById('first');
var secondDiv = document.getElementById('second');
var firstValue = { 'name':'Bart', 'status':'married', 'enlisted':true, 'healthy':true};
firstDiv.innerHTML = "Having the object with values:<br>";
Object.keys(firstValue).forEach(function (key) {
firstDiv.innerHTML += "<br>key: " + key + ", value: " + firstValue[key];
});
var result = _.defaults(firstValue, {'status':'single', 'fit':true, 'driversLicense':false});
secondDiv.innerHTML = "...we assign a set of new values. The exisiting keys wont be overwritten. Only the new keys and their values will be addes and we get:<br>";
Object.keys(firstValue).forEach(function (key) {
secondDiv.innerHTML += "<br>key: " + key + ", value: " + firstValue[key];
});
</script>
</body>
</html>