Skip to content

Commit

Permalink
+ object.value 支持路径取值
Browse files Browse the repository at this point in the history
  • Loading branch information
cloudcome committed Dec 19, 2016
1 parent b9c5048 commit c653c07
Show file tree
Hide file tree
Showing 3 changed files with 95 additions and 2 deletions.
2 changes: 1 addition & 1 deletion package.json
@@ -1,6 +1,6 @@
{
"name": "blear.utils.object",
"version": "1.0.5",
"version": "1.0.6",
"description": "object utils",
"scripts": {
"live": "browser-sync start --config bs-config.js",
Expand Down
72 changes: 71 additions & 1 deletion src/index.js
Expand Up @@ -277,4 +277,74 @@ var supply = exports.supply = function supply(_deep, _source, _target) {
}

return source;
};
};


/**
* 根据路径取值
* @param {Object} obj 对象
* @param {String|Array} path 路径
* @returns {*}
*
* @example
* object.value({a: 1}, 'a') === 1
* object.value({a: {b : 2}}, 'a.b') === 2
* object.value({a: {b : 2}}, ['a', 'b']) === 2
*/
exports.value = function (obj, path) {
var paths = [];

if (typeis.Array(path)) {
paths = path;
} else {
var point = '.';
var bracketStart = '[';
var bracketEnd = ']';
var start = 0;
var length = path.length;
var lastPath = '';
var push = function () {
if (lastPath) {
paths.push(lastPath);
}

lastPath = '';
};

while (start !== length) {
var char = path[start];

if (char === point) {
push();
} else if (char === bracketStart) {
push();
} else if (char === bracketEnd) {
//
} else {
lastPath += char;
}

start++;
}

push();
}

var i = 0;
var j = paths.length;
var ret;
var parent = obj;

for (; i < j; i++) {
var key = paths[i];

if (key in parent) {
ret = parent = parent[key];
} else {
ret = undefined;
break;
}
}

return ret;
};
23 changes: 23 additions & 0 deletions test/test.index.js
Expand Up @@ -315,4 +315,27 @@ describe('index.js', function () {
expect(o3.b[0]).toBe(1);
expect(o3.b[1]).toBe(3);
});

it('.value', function () {
var o1 = {
a: {
b: {
1: {
eee: 2
}
},
c: [{d: 2}]
}
};

expect(object.value(o1, 'a.b[1].eee')).toEqual(2);
expect(object.value(o1, 'a.b[1].eeee')).toEqual(undefined);
expect(object.value(o1, 'a.b[2].eee')).toEqual(undefined);
expect(object.value(o1, 'a.b[1]')).toEqual(o1.a.b[1]);
expect(object.value(o1, ['a', 'b', '1'])).toEqual(o1.a.b[1]);
expect(object.value(o1, ['a', 'b', '1', 'eee'])).toEqual(2);
expect(object.value(o1, ['a', 'b', '1', 'eeee'])).toEqual(undefined);
expect(object.value(o1, 'a.c[0]')).toEqual(o1.a.c[0]);
expect(object.value(o1, 'a.c[0].d')).toEqual(2);
});
});

0 comments on commit c653c07

Please sign in to comment.