文章内容

2019/8/12 10:00:22,作 者: 黄兵

npm object-path 使用

最近在研究Metronic v6.0.1,作者在解析json的时候使用的object-path包,以前没有遇到过,今天研究一下看看这个具体怎么使用。

安装方式:

NPM安装方式:

npm install object-path --save


下面是示例:

var obj = {
  a: {
    b: "d",
    c: ["e", "f"],
    '\u1200': 'unicode key',
    'dot.dot': 'key'
  }
};
 
var objectPath = require("object-path");
 
//get deep property
objectPath.get(obj, "a.b");  //returns "d"
objectPath.get(obj, ["a", "dot.dot"]);  //returns "key"
objectPath.get(obj, 'a.\u1200');  //returns "unicode key"
 
//get the first non-undefined value
objectPath.coalesce(obj, ['a.z', 'a.d', ['a','b']], 'default');
 
//empty a given path (but do not delete it) depending on their type,so it retains reference to objects and arrays.
//functions that are not inherited from prototype are set to null.
//object instances are considered objects and just own property names are deleted
objectPath.empty(obj, 'a.b'); // obj.a.b is now ''
objectPath.empty(obj, 'a.c'); // obj.a.c is now []
objectPath.empty(obj, 'a'); // obj.a is now {}
 
//works also with arrays
objectPath.get(obj, "a.c.1");  //returns "f"
objectPath.get(obj, ["a","c","1"]);  //returns "f"
 
//can return a default value with get
objectPath.get(obj, ["a.c.b"], "DEFAULT");  //returns "DEFAULT", since a.c.b path doesn't exists, if omitted, returns undefined
 
//set
objectPath.set(obj, "a.h", "m"); // or objectPath.set(obj, ["a","h"], "m");
objectPath.get(obj, "a.h");  //returns "m"
 
//set will create intermediate object/arrays
objectPath.set(obj, "a.j.0.f", "m");
 
//will insert values in array
objectPath.insert(obj, "a.c", "m", 1); // obj.a.c = ["e", "m", "f"]
 
//push into arrays (and create intermediate objects/arrays)
objectPath.push(obj, "a.k", "o");
 
//ensure a path exists (if it doesn't, set the default value you provide)
objectPath.ensureExists(obj, "a.k.1", "DEFAULT");
var oldVal = objectPath.ensureExists(obj, "a.b", "DEFAULT"); // oldval === "d"
 
//deletes a path
objectPath.del(obj, "a.b"); // obj.a.b is now undefined
objectPath.del(obj, ["a","c",0]); // obj.a.c is now ['f']
 
//tests path existence
objectPath.has(obj, "a.b"); // true
objectPath.has(obj, ["a","d"]); // false
 
//bind object
var model = objectPath({
  a: {
    b: "d",
    c: ["e", "f"]
  }
});
 
//now any method from above is supported directly w/o passing an object
model.get("a.b");  //returns "d"
model.get(["a.c.b"], "DEFAULT");  //returns "DEFAULT"
model.del("a.b"); // obj.a.b is now undefined
model.has("a.b"); // false

这个是截取的官方稳定示例,基本说明了基本的用法。


参考资料:

1、object-path


黄兵个人博客原创。

转载请注明出处:黄兵个人博客 - npm object-path 使用

分享到:

发表评论

评论列表