repl.it
@cjjenkinson/

defaults

JavaScript

fills in undefined properties in the destination object with own enumerable properties present in the source object, and returns destination

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
defaults = function(destination, source) {
	var prop;
	destination = destination || {};
	source = source || {}
	
	for (prop in source) {
		if (source.hasOwnProperty(prop)) {
			if (destination[prop] === undefined) {
				destination[prop] = source[prop];
			}
		}
	}

	return destination;
};

var defaultValues = {
	id: 123,
	count: 41,
	name: 'Destination Unknown',
	values: [1, 1, 2, 3, 5, 8, 13],
};

var destination = {
	name: undefined,
	tag: 'javascript',
	values: undefined,
};

var destinationWithDefaults = defaults(destination, defaultValues);
console.log(destinationWithDefaults);

var car = {
	wheels: 4,
	tires: 'standard',
	color: 'gray',
};

var usersCar = {
	color: 'blue',
};

var usersCarWithDefaults = defaults(usersCar, car);
console.log(usersCarWithDefaults);
Native Browser JavaScript