nested-property
Advanced tools
Comparing version 0.0.2 to 0.0.3
34
index.js
@@ -6,3 +6,3 @@ /** | ||
* | ||
* Copyright (c) 2014 Olivier Scherrer <pode.fr@gmail.com> | ||
* Copyright (c) 2014-2015 Olivier Scherrer <pode.fr@gmail.com> | ||
*/ | ||
@@ -15,4 +15,5 @@ "use strict"; | ||
set: setNestedProperty, | ||
get: getNestedProperty | ||
} | ||
get: getNestedProperty, | ||
has: hasNestedProperty | ||
}; | ||
@@ -44,2 +45,29 @@ /** | ||
/** | ||
* Tell if a nested object has a given property (or array a given index) | ||
* given an object such as a.b.c.d = 5, hasNestedProperty(a, "b.c.d") will return true. | ||
* @param {Object} object the object to get the property from | ||
* @param {String} property the path to the property as a string | ||
* @returns true if has (property in object), false otherwise | ||
*/ | ||
function hasNestedProperty(object, property) { | ||
if (object && typeof object == "object") { | ||
if (typeof property == "string" && property !== "") { | ||
var split = property.split("."); | ||
return split.reduce(function (obj, prop, idx, array) { | ||
if (idx == array.length - 1) { | ||
return !!(obj && prop in obj); | ||
} | ||
return obj && obj[prop]; | ||
}, object); | ||
} else if (typeof property == "number") { | ||
return property in object; | ||
} else { | ||
return false; | ||
} | ||
} else { | ||
return false; | ||
} | ||
} | ||
/** | ||
* Set the property of an object nested in one or more objects | ||
@@ -46,0 +74,0 @@ * If the property doesn't exist, it gets created. |
{ | ||
"name": "nested-property", | ||
"description": "Read or write an array or object's nested property via a string like 'my.nested.property'", | ||
"version": "0.0.2", | ||
"version": "0.0.3", | ||
"homepage": "https://github.com/cosmosio/nested-property", | ||
@@ -6,0 +6,0 @@ "licenses": [ |
Nested property | ||
============= | ||
Read or write an array or object's nested property via a string like 'my.nested.property' | ||
Read, write or test a data structure's nested property via a string like 'my.nested.property'. It works through arrays and objects. | ||
@@ -22,3 +22,3 @@ Installation | ||
You can get a nested property from an object: | ||
__You can get a nested property from an object:__ | ||
@@ -59,3 +59,3 @@ ```js | ||
You can set a nested property on an object: | ||
__You can set a nested property on an object:__ | ||
@@ -109,2 +109,26 @@ ```js | ||
__Finally, you can also test if a data structure has a nested property:__ | ||
```js | ||
var array = [ | ||
{ | ||
a: [0, 1] | ||
} | ||
]; | ||
nestedProperty.has(array, "0.a"); // true | ||
nestedProperty.has(array, "0.a.1"); // true | ||
nestedProperty.has(array, "0.a.2"); // false | ||
nestedProperty.has(array, "1.a.0"); // false | ||
``` | ||
CHANGELOG | ||
========= | ||
### 0.0.3 - 14 JAN 2015 | ||
* Add hasNestedProperty with tests and documentation | ||
LICENSE | ||
@@ -111,0 +135,0 @@ ======= |
Sorry, the diff of this file is not supported yet
7674
92
135