【问题标题】:Accessing a value of an Object in an Array nested in an Object with Polymer使用 Polymer 访问嵌套在对象中的数组中对象的值
【发布时间】:2016-10-26 13:45:02
【问题描述】:

我很抱歉这个不清楚的标题

问题
我有一个数据对象,其中包含一个联系人数组,其中包含多个对象。不幸的是,我无法访问嵌套对象的值。

找到here 的类似问题的答案解释了如何在 JavaScript 中访问它。 response.data.contacts[1].value 但是,使用 Polymer 只是打印代码而不是检索值。我相信问题来自我在绑定中使用的方括号。 {{response.data.contacts[1].value}}

下面我添加了我的数据,以阐明我所说的带有数组的对象中的对象值是什么意思,因为这有点令人困惑。我只想访问联系人数组中的值,而不是遍历所有这些值

{
  "data": {
    "contacts": [
     {
      "id": 259,
      "user_id": 248,
      "type": "phone",
      "value": "+1 (946) 315-2819",
      "created_at": "2016-08-24 18:12:30",
      "updated_at": "2016-10-24 13:03:33",
      "deleted_at": null
     },
     {
      "id": 260,
      "user_id": 248,
      "type": "phone",
      "value": "+1-979-427-7971",
      "created_at": "2015-12-08 04:10:19",
      "updated_at": "2016-10-24 13:03:33",
      "deleted_at": null
     },
    ]
  },
}

【问题讨论】:

  • 能否为创建response 变量的部分添加代码?

标签: javascript arrays object polymer polymer-1.0


【解决方案1】:

对于bind to a subproperty of an array item,使用array item path,如下所示:

{{response.data.contacts.1.value}}

HTMLImports.whenReady(() => {
  "use strict";

  Polymer({
    is: 'x-foo',
    properties: {
      response: {
        type: Object,
        value: () => ({
          "data": {
            "contacts": [{
              "id": 259,
              "user_id": 248,
              "type": "phone",
              "value": "+1 (946) 315-2819",
              "created_at": "2016-08-24 18:12:30",
              "updated_at": "2016-10-24 13:03:33",
              "deleted_at": null
            }, {
              "id": 260,
              "user_id": 248,
              "type": "phone",
              "value": "+1-979-427-7971",
              "created_at": "2015-12-08 04:10:19",
              "updated_at": "2016-10-24 13:03:33",
              "deleted_at": null
            }, ]
          },
        })
      }
    }
  });
});
<head>
  <base href="https://polygit.org/polymer+1.7.0/components/">
  <script src="webcomponentsjs/webcomponents-lite.min.js"></script>
  <link rel="import" href="polymer/polymer.html">
</head>
<body>
  <x-foo></x-foo>

  <dom-module id="x-foo">
    <template>
      <span>{{response.data.contacts.1.value}}</span>
    </template>
  </dom-module>
</body>

codepen

【讨论】:

  • 我确信我试过了,但我一定是有什么错误。谢谢@tony19!
猜你喜欢
  • 1970-01-01
  • 2022-01-08
  • 2021-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-11
  • 1970-01-01
相关资源
最近更新 更多