【问题标题】:Can't get value of Object in Javascript , nodejs, stripe library无法在 Javascript、nodejs、条带库中获取 Object 的值
【发布时间】:2015-12-30 15:44:00
【问题描述】:

我正在尝试使用这个简单的脚本从“客户”对象中获取值“状态”:

console.log(JSON.stringify(customer.subscriptions.data.plan.status));

当我执行这个函数时,控制台返回我:

TypeError: Cannot read property 'data' of undefined

“客户”对象:

customer: {
"object":"customer",
"created":xxxxxx,
"id":"xxxxxxx",
"livemode":false,
"description":null,
"email":"xxxx@xxxx.com",
"shipping":null,
"delinquent":false,
"metadata":{},
"subscriptions":{
    "object":"list",
    "total_count":1,
    "has_more":false,
    "url":"/v1/customers/xxxxxxxxx/subscriptions",
    "data":[{
        "id":"xxxxxxxxx",
        "plan":{
            "interval":"month",
            "name":"xxxxxx",
            "created":xxxxx,
            "amount":xxxxx,
            "currency":"eur",
            "id":"6month",
            "object":"plan",
            "livemode":false,
            "interval_count":6,
            "trial_period_days":null,
            "metadata":{},
            "statement_descriptor":null,
            "statement_description":null},
            "object":"subscription",
            "start":xxxxx,
            "status":"active",
            ...,

请帮助我。 谢谢。

【问题讨论】:

  • 请使用复制和粘贴引用对象,并完整引用对象,并且格式一致(而不是,例如,在"statement_description":null 之后具有近隐藏}),这使得事情相当误导。

标签: javascript node.js object stripe-payments


【解决方案1】:

错误与数据不匹配。应该是无法读取未定义的status。这是因为customer 确实有subscriptions,而subscriptions 确实 有data,但是你把data 当作它有一个plan 属性,它没有。 data 指的是一个数组,它的第一个条目有一个plan 属性。另请注意,status 不是plan 的属性,它是plan 是同一对象的属性。

所以访问 first 条目的 status 将是:

customer.subscriptions.data[0].status
// Note -------------------^^^

如果data 中有后续条目,它们将位于索引 1、2、3 等处。

例子:

var customer = {
  "object": "customer",
  "created": "xxxxxx",
  "id": "xxxxxxx",
  "livemode": false,
  "description": null,
  "email": "xxxx@xxxx.com",
  "shipping": null,
  "delinquent": false,
  "metadata": {},
  "subscriptions": {
    "object": "list",
    "total_count": 1,
    "has_more": false,
    "url": "/v1/customers/xxxxxxxxx/subscriptions",
    "data": [
      {
        "id": "xxxxxxxxx",
        "plan": {
          "interval": "month",
          "name": "xxxxxx",
          "created": "xxxxx",
          "amount": "xxxxx",
          "currency": "eur",
          "id": "6month",
          "object": "plan",
          "livemode": false,
          "interval_count": 6,
          "trial_period_days": null,
          "metadata": {},
          "statement_descriptor": null,
          "statement_description": null
        },
        "object": "subscription",
        "start": "xxxxx",
        "status": "active"
      }
    ]
  }
};
document.body.innerHTML = customer.subscriptions.data[0].status;

【讨论】:

    猜你喜欢
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-13
    • 2018-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多