【问题标题】:How to access nested array inside a JSON object from javascript如何从 javascript 访问 JSON 对象内的嵌套数组
【发布时间】:2018-08-28 17:03:11
【问题描述】:

我正在使用一个 json 对象,该对象具有嵌套数组以及带有空格的名称,例如 Account ID。我只需要在我的 Vue.js 应用程序中显示 Account ID。我能够得到我的整个 response.data json 对象,但不太确定当它像下面的示例一样嵌套时如何只得到 Account ID

JSON

"response": {
    "result": {
      "Accounts": {
        "row": [
          {
            "no": "1",
            "FL": [
              {
                "val": "ACCOUNT ID",
                "content": "123456789"
              },
              ...

Vue.js

<script>
        import axios from "axios";
        export default {
            name: 'HelloWorld',
            data () {
                return {
                    accounts: [],
                    accountIDs: []
                }
            },
            mounted() {
              var self = this;
              axios.get('https://MYAPIGETREQUEST')
                .then( function(res){
                    self.accounts = res.data;
                    self.accountIDs = //This is where I want to get the Account ID
                    console.log('Data: ', res.data);
                })
                .catch( function(error){
                    console.log('Error: ', error);
                })
            }
        }
    </script>

【问题讨论】:

  • 如果知道json数据结构的形状,为什么不能直接访问呢?使用 es6 解构,就更简单了
  • 我确实觉得应该这么简单,但不确定我做错了什么。我正在尝试在文本区域中显示“帐户 ID”,以查看我是否正在获取数据但没有出现任何内容。我正在尝试 res.data.response.result.row[0].FL[0].val["ACCOUNT ID'].content,但我知道我做错了什么
  • console.log('Data: ', res.data); 的结果是什么? ?
  • 我不认为是 res.data。它应该是 res.response 或 res.result
  • 你只需要走下对象结构...jsfiddle.net/7jkuhuah/3

标签: javascript json vue.js axios


【解决方案1】:

试试这样的

if(res.data.response.result.Accounts.row[0].FL[0].val === 'ACCOUNT ID') {

   self.accountIDs = res.data.response.result.Accounts.row[0].FL[0].content;

   ...
}

【讨论】:

  • 我意识到我丢失了部分数据结构。我有 res.data.result... 但我需要 res.data.response.result... 但是,如果我需要这样做,我确实喜欢这个解决方案,以便对我的响应对象进行额外验证。
【解决方案2】:

你也可以试试这样的:

let rowAccounts = response.result.Accounts.row
   .map(row => row.FL
       .filter(FL => FL.val === 'ACCOUNT ID')
       .map(acc => acc.content)
    );

self.accountIDs = [].concat.apply([], rowAccounts);

rowAccounts 中,您会得到每行的帐户数组,例如:

[
   0: ['acc row 1', 'another acc row1'],
   1: ['acc row 2'....]
]

现在这一切都取决于您喜欢的实现方式。

【讨论】:

    猜你喜欢
    • 2017-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    相关资源
    最近更新 更多