1e53eb01162c82cbdf3f6d89076f8721374b266c
[platform/framework/web/crosswalk-tizen.git] /
1 # object #
2
3 Object utilities.
4
5
6
7 ## bindAll(obj, [...methodNames]):void
8
9 Bind methods of the target object to always execute on its own context
10 (ovewritting the original function).
11
12 See: [function/bind](./function.html#bind)
13
14 ```js
15 var view = {
16     name: 'Lorem Ipsum',
17     logNameOnClick: function() {
18         console.log(this.name);
19     }
20 };
21
22 // binds all methods by default
23 bindAll(view);
24 jQuery('#docs').on('click', view.logNameOnClick);
25 ```
26
27 You can also specify the list of methods that you want to bind (in case you
28 just want to bind a few of them).
29
30 ```js
31 // only the listed methods will be bound to `obj` context
32 bindAll(obj, 'logNameOnClick', 'doAwesomeStuffOnDrag');
33 ```
34
35
36
37 ## contains(obj, value):Boolean
38
39 Similar to [Array/contains](array.html#contains). Checks if Object contains
40 value.
41
42 ```js
43 var obj = {
44     a: 1,
45     b: 2,
46     c: 'bar'
47 };
48 contains(obj, 2);      // true
49 contains(obj, 'foo');  // false
50 ```
51
52
53
54 ## deepFillIn(target, ...objects):Object
55
56 Fill missing properties recursively.
57
58 It's different from `deepMixIn` since it won't override any existing property.
59 It's also different from `merge` since it won't clone child objects during the
60 process.
61
62 It returns the target object and mutates it in place.
63
64 See: [`fillIn()`](#fillIn), [`deepMixIn()`](#deepMixIn), [`merge()`](#merge)
65
66 ```js
67 var base = {
68     foo : {
69         bar : 123
70     },
71     lorem : 'ipsum'
72 };
73 var options = deepFillIn({foo : { baz : 45 }, lorem : 'amet'}, base);
74 // > {foo: {bar:123, baz : 45}, lorem : 'amet'}
75 ```
76
77
78
79 ## deepMatches(target, pattern):Boolean
80
81 Recursively checks if object contains all properties/value pairs. When both
82 the target and pattern values are arrays, it checks that the target value
83 contain matches for all the items in the pattern array (independent of order).
84
85 ```js
86 var john = {
87     name: 'John',
88     age: 22,
89     pets: [
90         { type: 'cat', name: 'Grumpy Cat' },
91         { type: 'dog', name: 'Hawk' }
92     ]
93 };
94
95 deepMatches(john, { name: 'John' }); // true
96 deepMatches(john, { age: 21 }); // false
97 deepMatches(john, { pets: [ { type: 'cat' } ] }); // true
98 deepMatches(john, { pets: [ { name: 'Hawk' } ] }); // true
99 deepMatches(john, { pets: [ { name: 'Hairball' } ] }); // false
100 ```
101
102 See [`matches()`](#matches)
103
104
105
106 ## deepMixIn(target, ...objects):Object
107
108 Mixes objects into the target object, recursively mixing existing child objects
109 as well.
110
111 It will only recursively mix objects if both (existing and new) values are
112 plain objects.
113
114 Returns the target object. Like [`merge()`](#merge), but mutates the target
115 object, and does not clone child objects.
116
117 ```js
118 var target = {
119     foo: {
120         name: "foo",
121         id: 1
122     }
123 };
124
125 deepMixIn(target, { foo: { id: 2 } });
126 console.log(target); // { foo: { name: "foo", id: 2 } }
127 ```
128
129 See: [`mixIn()`](#mixIn), [`merge()`](#merge), [`deepFillIn()`](#deepFillIn)
130
131
132
133 ## equals(a, b, [callback]):Boolean
134
135 Tests whether two objects contain the same keys and values.
136
137 `callback` specifies the equality comparison function used to compare the
138 values. It defaults to using [lang/is](lang.html#is).
139
140 It will only check the keys and values contained by the objects; it will not
141 check the objects' prototypes. If either of the values are not objects, they
142 will be compared using the `callback` function.
143
144 ```js
145 equals({}, {}); // true
146 equals({ a: 1 }, { a: 1 }); // true
147 equals({ a: 1 }, { a: 2 }); // false
148 equals({ a: 1, b: 2 }, { a: 1 }); // false
149 equals({ a: 1 }, { a: 1, b: 2 }); // false
150 equals(null, null); // true
151 equals(null, {}); // false
152 equals({ a: 1 }, { a: '1' }, function(a, b) { return a == b; }); // true
153 ```
154
155 See: [array/equals](array.html#equals), [lang/deepEquals](lang.html#deepEquals)
156
157
158 ## every(obj, callback, [thisObj]):Boolean
159
160 Similar to [Array/every](array.html#every). Tests whether all properties in the
161 object pass the test implemented by the provided callback.
162
163 ```js
164 var obj = {
165     a: 1,
166     b: 2,
167     c: 3,
168     d: 'string'
169 };
170
171 every(obj, isNumber); // false
172 ```
173
174
175
176 ## fillIn(obj, ...default):Object
177
178 Fill in missing properties in object with values from the *defaults* objects.
179
180     var base = {
181         foo : 'bar',
182         num : 123
183     };
184
185     fillIn({foo:'ipsum'}, base); // {foo:'ipsum', num:123}
186
187 PS: it allows merging multiple objects at once, the first ones will take
188 precedence.
189
190 See: [`mixIn()`](#mixIn), [`merge()`](#merge), [`deepFillIn()`](#deepFillIn)
191
192
193
194 ## filter(obj, callback, [thisObj])
195
196 Returns a new object containing all properties where `callback` returns true,
197 similar to Array/filter. It does not use properties from the object's
198 prototype.
199
200 Callback receives the same arguments as `forOwn()`.
201
202 See: [`forOwn()`](#forOwn), [`forIn()`](#forIn), [`pick()`](#pick)
203
204 ```js
205 var obj = {
206     foo: 'value',
207     bar: 'bar value'
208 };
209
210 // returns { bar: 'bar value' }
211 filter(obj, function(v) { return value.length > 5; });
212
213 // returns { foo: 'value' }
214 filter(obj, function(v, k) { return k === 'foo'; });
215 ```
216
217
218
219 ## find(obj, callback, [thisObj])
220
221 Loops through all the properties in the Object and returns the first one that
222 passes a truth test (callback), similar to [Array/find](array.html#find).
223 Unlike Array/find, order of iteration is not guaranteed.
224
225 ```js
226 var obj = {
227     a: 'foo',
228     b: 12
229 };
230
231 find(obj, isString); // 'foo'
232 find(obj, isNumber); // 12
233 ```
234
235
236
237 ## forIn(obj, callback[, thisObj])
238
239 Iterate over all properties of an Object, similar to
240 [Array/forEach](array.html#forEach).
241
242 It [avoids don't enum bug on IE](https://developer.mozilla.org/en/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug).
243 It **will** iterate over inherited (enumerable) properties from the prototype.
244
245 It allows exiting the iteration early by returning `false` on the callback.
246
247 See: [`forOwn()`](#forOwn), [`keys()`](#keys), [`values()`](#values)
248
249 ### Callback arguments
250
251 Callback will receive the following arguments:
252
253  1. Property Value (*)
254  2. Key name (String)
255  3. Target object (Object)
256
257 ### Example
258
259 ```js
260 function Foo(){
261     this.foo = 1;
262     this.bar = 2;
263 }
264
265 Foo.prototype.lorem = 4;
266
267 var obj = new Foo();
268
269 var result = 0;
270 var keys = [];
271
272 forIn(obj, function(val, key, o){
273     result += val;
274     keys.push(key);
275 });
276
277 console.log(result); // 7
278 console.log(keys);   // ['foo', 'bar', 'lorem']
279 ```
280
281
282
283 ## forOwn(obj, callback[, thisObj])
284
285 Iterate over all own properties from an Object, similar to
286 [Array/forEach](array.html#forEach).
287
288 It [avoids don't enum bug on IE](https://developer.mozilla.org/en/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug).
289 Notice that it **won't** iterate over properties from the prototype.
290
291 It allows exiting the iteration early by returning `false` on the callback.
292
293 See: [`forIn()`](#forIn), [`keys()`](#keys), [`values()`](#values)
294
295 ### Callback arguments
296
297 Callback will receive the following arguments:
298
299  1. Property Value (*)
300  2. Key name (String)
301  3. Target object (Object)
302
303 ### Example
304
305 ```js
306 function Foo(){
307     this.foo = 1;
308     this.bar = 2;
309 }
310
311 // will be ignored
312 Foo.prototype.lorem = 4;
313
314 var obj = new Foo();
315
316 var result = 0;
317 var keys = [];
318
319 forOwn(obj, function(val, key, o){
320     result += val;
321     keys.push(key);
322 });
323
324 console.log(result); // 3
325 console.log(keys);   // ['foo', 'bar']
326 ```
327
328
329
330 ## functions(obj):Array
331
332 Returns a sorted list of all enumerable properties that have function values
333 (including inherited properties).
334
335 ```js
336 var obj = {
337     foo : function(){},
338     bar : 'baz'
339 };
340 functions(obj); // ['foo']
341 ```
342
343
344
345 ## get(obj, propName):*
346
347 Returns nested property value. Will return `undefined` if property doesn't
348 exist.
349
350 See: [`set()`](#set), [`namespace()`](#namespace), [`has()`](#has)
351
352 ```js
353 var lorem = {
354         ipsum : {
355             dolor : {
356                 sit : 'amet'
357             }
358         }
359     };
360
361 get(lorem, 'ipsum.dolor.sit'); // "amet"
362 get(lorem, 'foo.bar');         // undefined
363 ```
364
365
366
367 ## has(obj, propName):Boolean
368
369 Checks if object contains a child property. Useful for cases where you need to
370 check if an object contain a *nested* property. It will get properties
371 inherited by the prototype.
372
373 see: [`hasOwn()`](#hasOwn), [`get()`](#get)
374
375 ```js
376 var a = {
377         b : {
378             c : 123
379         }
380     };
381
382 has(a, 'b.c');   // true
383 has(a, 'foo.c'); // false
384 ```
385
386 ### Common use case
387
388 ```js
389 if( has(a, 'foo.c') ){ // false
390     // ...
391 }
392
393 if( a.foo.c ){ // ReferenceError: `foo` is not defined
394     // ...
395 }
396 ```
397
398
399
400 ## hasOwn(obj, propName):Boolean
401
402 Safer `Object.hasOwnProperty`. Returns a boolean indicating whether the object
403 has the specified property.
404
405 see: [`has()`](#has)
406
407 ```js
408 var obj = {
409     foo: 1,
410     hasOwnProperty : 'bar'
411 };
412
413 obj.hasOwnProperty('foo'); // ERROR! hasOwnProperty is not a function
414
415 hasOwn(obj, 'foo');            // true
416 hasOwn(obj, 'hasOwnProperty'); // true
417 hasOwn(obj, 'toString');       // false
418 ```
419
420
421
422 ## keys(obj):Array
423
424 Returns an array of all own enumerable properties found upon a given object.
425 It will use the native `Object.keys` if present.
426
427 PS: it won't return properties from the prototype.
428
429 See: [`forOwn()`](#forOwn), [`values()`](#values)
430
431 ```js
432 var obj = {
433     foo : 1,
434     bar : 2,
435     lorem : 3
436 };
437 keys(obj); // ['foo', 'bar', 'lorem']
438 ```
439
440
441
442 ## map(obj, callback, [thisObj]):Object
443
444 Returns a new object where the property values are the result of calling the
445 callback for each property in the original object, similar to Array/map.
446
447 The callback function receives the same arguments as in `forOwn()`.
448
449 See: [`forOwn()`](#forOwn)
450
451 ```js
452 var obj = { foo: 1, bar: 2 },
453     data = { foo: 0, bar: 1 };
454
455 map(obj, function(v) { return v + 1; }); // { foo: 2, bar: 3 }
456 map(obj, function(v, k) { return k; }); // { foo: "foo", bar: "bar" }
457 map(obj, function(v, k) { return this[k]; }, data); // { foo: 0, bar: 1 }
458 ```
459
460
461
462 ## matches(obj, props):Boolean
463
464 Checks if object contains all properties/values pairs. Useful for validation
465 and filtering.
466
467 ```js
468 var john = {age:25, hair:'long', beard:true};
469 var mark = {age:27, hair:'short', beard:false};
470 var hippie = {hair:'long', beard:true};
471 matches(john, hippie); // true
472 matches(mark, hippie); // false
473 ```
474
475 See [`deepMatches()`](#deepMatches)
476
477
478
479 ## merge(...objects):Object
480
481 Deep merges objects. Note that objects and properties will be cloned during the
482 process to avoid undesired side effects. It return a new object and won't
483 affect source objects.
484
485 ```js
486 var obj1 = {a: {b: 1, c: 1, d: {e: 1, f: 1}}};
487 var obj2 = {a: {b: 2, d : {f : 'yeah'} }};
488
489 merge(obj1, obj2); // {a: {b : 2, c : 1, d : {e : 1, f : 'yeah'}}}
490 ```
491
492 See: [`deepMixIn()`](#deepMixIn), [`deepFillIn()`](#deepFillIn)
493
494
495
496 ## max(obj[, iterator]):*
497
498 Returns maximum value inside object or use a custom iterator to define how
499 items should be compared. Similar to [Array/max](array.html#max).
500
501 See: [`min()`](#min)
502
503 ```js
504 max({a: 100, b: 2, c: 1, d: 3, e: 200}); // 200
505 max({a: 'foo', b: 'lorem', c: 'amet'}, function(val){
506     return val.length;
507 }); // 'lorem'
508 ```
509
510
511
512 ## min(obj[, iterator]):*
513
514 Returns minimum value inside object or use a custom iterator to define how
515 items should be compared. Similar to [Array/min](array.html#min).
516
517 See: [`max()`](#max)
518
519 ```js
520 min({a: 100, b: 2, c: 1, d: 3, e: 200}); // 1
521 min({a: 'foo', b: 'lorem', c: 'amet'}, function(val){
522     return val.length;
523 }); // 'foo'
524 ```
525
526
527
528 ## mixIn(target, ...objects):Object
529
530 Combine properties from all the objects into first one.
531
532 This method affects target object in place, if you want to create a new Object
533 pass an empty object as first parameter.
534
535 ### Arguments
536
537  1. `target` (Object)        : Target Object.
538  2. `...objects` (...Object) : Objects to be combined (0...n objects).
539
540 ### Example
541
542 ```js
543 var a = {foo: "bar"};
544 var b = {lorem: 123};
545
546 mixIn({}, a, b); // {foo: "bar", lorem: 123}
547 console.log(a);  // {foo: "bar"}
548
549 mixIn(a, b);     // {foo: "bar", lorem: 123}
550 console.log(a);  // {foo: "bar", lorem: 123}
551 ```
552
553 See: [`fillIn()`](#fillIn), [`merge()`](#merge)
554
555
556
557
558 ## namespace(obj, propName):Object
559
560 Creates an empty object inside namespace if not existent. Will return created
561 object or existing object.
562
563 See: [`get()`](#get), [`set()`](#set)
564
565 ```js
566 var obj = {};
567 namespace(obj, 'foo.bar'); // {}
568 console.log(obj);          // {foo:{bar:{}}}
569 ```
570
571
572 ## omit(obj, ...keys):Object
573
574 Return a copy of the object without the blacklisted keys.
575
576 See: [`filter()`](#filter)
577
578 ```js
579 var user = {
580     firstName : 'John',
581     lastName : 'Doe',
582     dob : '1985/07/23',
583     gender : 'male'
584 };
585
586 // can pass an array of keys as second argument
587 var keys = ['firstName', 'dob']
588 omit(user, keys); // {lastName : 'Doe', gender : 'male'}
589
590 // or multiple arguments
591 omit(user, 'firstName', 'lastName'); // {dob : '1985/07/23', gender : 'male'}
592 ```
593
594
595
596 ## pick(obj, ...keys):Object
597
598 Return a copy of the object that contains only the whitelisted keys.
599
600 See: [`filter()`](#filter)
601
602 ```js
603 var user = {
604     firstName : 'John',
605     lastName : 'Doe',
606     dob : '1985/07/23',
607     gender : 'male'
608 };
609
610 // can pass an array of keys as second argument
611 var keys = ['firstName', 'dob']
612 pick(user, keys); // {firstName:"John", dob: "1985/07/23"}
613
614 // or multiple arguments
615 pick(user, 'firstName', 'lastName'); // {firstName:"John", lastName: "Doe"}
616 ```
617
618
619
620 ## pluck(obj, propName):Object
621
622 Extract an object containing property values with keys as they appear in the
623 passed object.
624
625 ```js
626 var users = {
627     first: {
628         name : 'John',
629         age : 21
630     },
631     second: {
632         name : 'Mary',
633         age : 25
634     }
635 };
636
637 pluck(users, 'name'); // {first: 'John', second: 'Mary'} );
638 pluck(users, 'age');  // {first: 21, second: 25} );
639 ```
640
641
642
643 ## reduce(obj, callback, initial, [thisObj]):*
644
645 Similar to [Array/reduce](array.html#reduce).
646
647 Apply a function against an accumulator and each property of the object (order
648 is undefined) as to reduce it to a single value.
649
650 ```js
651 var obj = {a: 1, b: 2, c: 3, d: 4};
652
653 function sum(prev, cur, key, list) {
654     compare1.push(prev);
655     return prev + cur;
656 }
657
658 reduce(obj, sum); // 10
659 ```
660
661
662
663 ## reject(obj, callback, thisObj):Object
664
665 Returns a new object containing all properties where `callback` returns true,
666 similar to [Array/reject](array.html#reject). It does not use properties from
667 the object's prototype. Opposite of [`filter()`](#filter).
668
669 See [`filter()`](#filter)
670
671 ### Example
672
673 ```js
674 var obj = {a: 1, b: 2, c: 3, d: 4, e: 5};
675 reject(obj, function(x) { return (x % 2) !== 0; }); // {b: 2, d: 4}
676 ```
677
678
679
680 ## values(obj):Array
681
682 Returns an array of all own enumerable properties values found upon a given object.
683
684 PS: it won't return properties from the prototype.
685
686 See: [`forOwn()`](#forOwn), [`keys()`](#keys)
687
688 ```js
689 var obj = {
690     foo : 1,
691     bar : 2,
692     lorem : 3
693 };
694 values(obj); // [1, 2, 3]
695 ```
696
697
698
699 ## set(obj, propName, value)
700
701 Sets a nested property value.
702
703 See: [`get()`](#get), [`namespace()`](#namespace)
704
705 ```js
706 var obj = {};
707 set(obj, 'foo.bar', 123);
708 console.log(obj.foo.bar); // 123
709 console.log(obj);         // {foo:{bar:123}}
710 ```
711
712
713
714 ## size(obj):Number
715
716 Returns the count of own enumerable properties found upon a given object.
717
718 PS: it won't return properties from the prototype.
719
720 See: [`forOwn()`](#forOwn), [`keys()`](#keys)
721
722 ```js
723 var obj = {
724     foo : 1,
725     bar : 2,
726     lorem : 3
727 };
728 size(obj); // 3
729 ```
730
731
732
733 ## some(obj, callback, [thisObj]):Boolean
734
735 Similar to [Array/some](array.html#some). Tests whether any properties in the
736 object pass the test implemented by the provided callback.
737
738 ```js
739 var obj = {
740     a: 1,
741     b: 2,
742     c: 3,
743     d: 'string'
744 };
745
746 some(obj, isNumber); // true
747 ```
748
749
750
751 ## unset(obj, propName):Boolean
752
753 Delete object property if existent and returns a boolean indicating succes. It
754 will also return `true` if property doesn't exist.
755
756 Some properties can't be deleted, to understand why [check this
757 article](http://perfectionkills.com/understanding-delete/).
758
759 See: [`set()`](#set)
760
761 ```js
762 var lorem = {
763         ipsum : {
764             dolor : {
765                 sit : 'amet'
766             }
767         }
768     };
769
770 unset(lorem, 'ipsum.dolor.sit'); // true
771 console.log(lorem.ipsum.dolor);  // {}
772 unset(lorem, 'foo.bar');         // true
773 ```
774
775
776
777 ## result(object, property):Mixed
778
779 Evaluates an objects property and returns result.
780
781 ```js
782 var person = {
783     name: 'john',
784
785     mood: function() {
786         // some dynamic calculated property.
787         return 'happy';
788     }
789 };
790
791 var name = result(person, 'name'), // john
792     mood = result(person, 'mood'); // happy
793 ```