Nodejs 写了一个模块 ettr,通过字符串描述访问嵌套属性
Nodejs 写了一个模块 ettr,通过字符串描述访问嵌套属性
地址在:https://github.com/alsotang/ettr
场景: 有时在得到一个 Object 之后,需要去访问里面嵌套的属性,但没法通过 literal 的方式来访问,于是就诞生了这样的一个库。
install
npm install ettr
usage
Assume obj
is
{
a: {
b: {
c: 1,
d: 2,
}
}
}
.get(obj, attr)
ettr.get(obj, 'a.b.c')
.should.equal(1);
ettr.get(obj, ‘a[b][“c”]’)
.should.equal(1);
.set(obj, attr, value)
ettr.set(obj, 'a.b.c', 5);
obj.a.b.c.should.equal(5);
.incr(obj, attr, value, defaultValue)
ettr.incr(obj, 'a.b.z', 1, 100);
ettr.incr(obj, 'a.b.z', 1, 100);
obj.a.b.z.should.equal(102);
license
MIT
你可以再加上 ->
这个连接符 2333333。
这个模块式为防止读取内嵌对象时,出现以下问题而设计的吗?
a={
a:{}
};
var x = a.b.c;
TypeError: Cannot read property 'c' of undefined
建议跟py一样,读取get(obj, attr)时,第三个参数加上默认值
get(obj, attr, defaultValue)
codewars有这么一个题 http://www.codewars.com/kata/527a6e602a7db3456e000a2b
有best practice,我赶脚foreach不怎么好
Object.prototype.hash = function(string) {
var obj = this;
string.split(".").forEach(function(el) {
try {
obj = obj[el];
}
catch(e) {
obj = undefined;
}
});
return obj;
}
my_solution
// return the nested property value if it exists,
// otherwise return undefined
Object.prototype.hash = function(string) {
// hash()
if(!string) return this;
if(typeof string === ‘string’)
string = string.split(’.’)
var ret = this[string[0]];
if(string.length === 1){
return ret
}
else{
return ret
? ret.hash(string.slice(1))
: ret
}
}
找着一个很贱的写法
Object.prototype.hash = function(string) {
var fn = new Function("try { return this." + string + "; } catch(e) {return undefined;} ");
return fn.call(this);
}
Nodejs 写了一个模块 ettr,通过字符串描述访问嵌套属性
场景:
在处理对象时,有时我们需要访问嵌套属性。如果这些属性层级很深,通过点或方括号的方式逐级访问可能会比较繁琐。为了简化这个过程,我开发了一个名为 ettr
的库,可以让你通过字符串描述直接访问和修改嵌套属性。
安装
npm install ettr
使用方法
假设我们有一个嵌套对象 obj
:
const obj = {
a: {
b: {
c: 1,
d: 2,
}
}
};
获取嵌套属性
使用 .get()
方法可以通过字符串描述获取嵌套属性的值:
const ettr = require('ettr');
// 通过点符号访问
console.log(ettr.get(obj, 'a.b.c')); // 输出:1
// 通过方括号访问
console.log(ettr.get(obj, 'a[b]["c"]')); // 输出:1
设置嵌套属性
使用 .set()
方法可以通过字符串描述设置嵌套属性的值:
ettr.set(obj, 'a.b.c', 5);
console.log(obj.a.b.c); // 输出:5
增加嵌套属性的值
使用 .incr()
方法可以通过字符串描述增加嵌套属性的值。如果该属性不存在,则使用默认值进行初始化:
ettr.incr(obj, 'a.b.z', 1, 100);
ettr.incr(obj, 'a.b.z', 1, 100);
console.log(obj.a.b.z); // 输出:102
许可证
本项目采用 MIT 许可证。
GitHub 地址
你可以访问 GitHub 查看源码和更多详细信息。