index.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. function getpath(obj, path) {
  2. path = path || "";
  3. var arr = path.split(".");
  4. var t = obj;
  5. var done = false;
  6. if (arr.length) {
  7. while (arr.length && !done) {
  8. var check = arr.shift();
  9. if (check !== "") {
  10. t = t[check];
  11. }
  12. if (typeof t !== "object") {
  13. done = true;
  14. }
  15. }
  16. }
  17. return t;
  18. }
  19. function setpath(obj, path, value) {
  20. if (typeof obj !== "object" || !obj) {
  21. throw new Error("obj is not Object");
  22. }
  23. if (typeof path !== "string" || path === "") {
  24. throw new Error("path must be string with length > 0");
  25. }
  26. var arr = path.split(".");
  27. var done = false;
  28. var t = obj;
  29. if (arr.length > 1) {
  30. while (arr.length && t && !done) {
  31. var check = arr.shift();
  32. if (typeof t[check] === "object" && arr.length > 0) {
  33. t = t[check];
  34. } else {
  35. done = true;
  36. arr.unshift(check);
  37. }
  38. }
  39. var xt = t;
  40. while (arr.length) {
  41. var tt = arr.shift();
  42. if (arr.length) { //go deeper
  43. xt = xt[tt] = {};
  44. } else {
  45. //last
  46. xt[tt] = value;
  47. }
  48. }
  49. } else {
  50. if (arr.length === 1 && arr[0] !== "") {
  51. t[arr[0]] = value;
  52. }
  53. }
  54. }
  55. function sort_by_1_col(a, b) {
  56. return a[0] > b[0] ? -1 : a[0] < b[0] ? 1 : 0;
  57. }
  58. function sort_by_1_col_alpha(a, b) {
  59. var x = a[0].toLowerCase(),
  60. y = b[0].toLowerCase();
  61. return x < y ? -1 : x > y ? 1 : 0;
  62. }
  63. function query(obj, str) {
  64. console.log(obj);
  65. console.log(str);
  66. }
  67. function flatten(obj, pre) {
  68. var pre = pre || "";
  69. var r = [];
  70. for (var i in obj) {
  71. if (typeof(obj[i]) === "object") {
  72. r = r.concat(flatten(obj[i], (pre.length > 0 ? pre + "." : "") + i));
  73. } else {
  74. r.push([(pre.length > 0 ? pre + "." : "") + i, "" + obj[i]]);
  75. }
  76. }
  77. r.sort(sort_by_1_col_alpha)
  78. return r;
  79. }
  80. module.exports = {
  81. get: getpath,
  82. set: setpath,
  83. flatten: flatten,
  84. query: query
  85. }