9

我不想使用已知的点表示法访问深层对象,而是想做相反的事情:从深层对象的键构建点表示法字符串。

所以给定以下 JSON 对象:

{
  great:{
    grand:{
      parent:{
        child:1
      },
      parent2:1
    }
  }
}

我想获得以下路径数组:

[
  "great.grand.parent.child",
  "great.grand.parent2"
]

提前致谢!

4

2 回答 2

7

试试这个。但我不知道你为什么需要这个。

function path(a) {
  var list = [];
  (function(o, r) {
    r = r || '';
    if (typeof o != 'object') {
      return true;
    }
    for (var c in o) {
      if (arguments.callee(o[c], r + "." + c)) {
        list.push(r.substring(1) + "." + c);
      }
    }
    return false;
  })(a);
  return list;
}
var a = {
  great:{
    grand:{
      parent:{
        child:1
      },
      parent2:1
    }
  }
};
console.log(JSON.stringify(path(a)));
于 2012-11-28T04:21:59.683 回答
2
var path = function (a) {
  var list = [];
  (function(o, r) {
    r = r || '';
    if (_.isArray(o)) {
      return true;
    }
    for (var c in o) {
      if (arguments.callee(o[c], r + (r!=""?"[":"") + c + (r!=""?"]":""))) {
        list.push(r + (r!=""?"[":"") + c + (r!=""?"]":""));
      }
    }
    return false;
  })(a);
  return list;
};

使用这样的输入(输入错误的深层 JSON 对象):

{
    "email": [
      "Enter a valid email."
    ],
    "billing": {
      "name": [
        "Enter a billing name."
      ],
      "line1": [
        "Enter a street address or PO box."
      ],
      "city": [
        "Enter a city."
      ],
      "state": [
        "Enter your state abbreviation."
      ],
      "zip": [
        "Enter a valid 5-digit zip."
      ]
    },
    "shipping": {
      "name": [
        "Enter a billing name."
      ],
      "line1": [
        "Enter a street address or PO box."
      ],
      "city": [
        "Enter a city."
      ],
      "state": [
        "Enter your state abbreviation."
      ],
      "zip": [
        "Enter a valid 5-digit zip."
      ]
    },
    "payment": {
      "number": [
        "Enter a valid credit card number."
      ],
      "exp_month": [
        "Enter a valid expiration month."
      ],
      "exp_year": [
        "Enter a valid expiration year."
      ],
      "cvc": [
        "Enter a valid CVC."
      ]
    }
 }

您会得到这样的输出(数组表示法中的输入名称,通过客户端模板在其中附加错误)

["email", "billing[name]", "billing[line1]", "billing[city]", "billing[state]", "billing[zip]", "shipping[name]", "shipping[line1]", "shipping[city]", "shipping[state]", "shipping[zip]", "payment[number]", "payment[exp_month]", "payment[exp_year]", "payment[cvc]"]
于 2012-11-28T18:53:56.693 回答