【问题标题】:JSON.stringify different from direct access to object property, strongloopJSON.stringify 不同于直接访问对象属性,strongloop
【发布时间】:2015-08-22 06:22:18
【问题描述】:

我使用 strongloop 来构建我的 api。 在特定路线上,查询包括模型的关系。我得到了一组我想要安排的对象。 在这个特殊的安排功能中,我面临以下问题。 该函数接收一个名为“item”的对象,其中包含一个“trans”字段(该字段是另一个对象的数组)。 这段代码:

console.log(JSON.stringify(item, null, 2));

产生这个结果:

{
  "id": 1,
  "created": "2015-08-19T21:04:16.000Z",
  "updated": null,
  "authorid": 0,
  "likes": 0,
  "shares": 0,
  "fav": 0,
  "validated": 0,
  "comments": 0,
  "trans": [
    {
      "text": "Première question en français",
      "questionId": 1
    }
  ],
  "answers": [
    {
      "id": 1,
      "questionid": 1,
      "questionId": 1,
      "trans": [
        {
          "text": "q1 : reponse 1 en francais",
          "answerId": 1
        }
      ]
    },
    {
      "id": 2,
      "questionid": 1,
      "questionId": 1,
      "trans": [
        {
          "text": "q1 : reponse 2 en francais",
          "answerId": 2
        }
      ]
    }
  ]
}

这个问题是当我尝试到达这部分时:

item.trans[0].text

控制台说 “item.trans 未定义”,当我尝试这段代码时:

console.log(item.trans);

我有这个结果:

function (condOrRefresh, options, cb) {
    if (arguments.length === 0) {
      if (typeof f.value === 'function') {
        return f.value(self);
      } else if (self.__cachedRelations) {
        return self.__cachedRelations[name];
      }
    } else {
      if (typeof condOrRefresh === 'function'
        && options === undefined && cb === undefined) {
        // customer.orders(cb)
        cb = condOrRefresh;
        options = {};
        condOrRefresh = undefined;
      } else if (typeof options === 'function' && cb === undefined) {
        // customer.orders(condOrRefresh, cb);
        cb = options;
        options = {};
      }
      options = options || {}
      // Check if there is a through model
      // see https://github.com/strongloop/loopback/issues/1076
      if (f._scope.collect &&
        condOrRefresh !== null && typeof condOrRefresh === 'object') {
        //extract the paging filters to the through model
        ['limit','offset','skip','order'].forEach(function(pagerFilter){
            if(typeof(condOrRefresh[pagerFilter]) !== 'undefined'){
                f._scope[pagerFilter] = condOrRefresh[pagerFilter];
                delete condOrRefresh[pagerFilter];
            }
        });
        // Adjust the include so that the condition will be applied to
        // the target model
        f._scope.include = {
          relation: f._scope.collect,
          scope: condOrRefresh
        };
        condOrRefresh = {};
      }
      return definition.related(self, f._scope, condOrRefresh, options, cb);
    }
  } 

在这种情况下,我怎样才能简单地访问“trans”属性来获取里面的文本? (在 js 中并不容易) 提前致谢。

【问题讨论】:

    标签: javascript json strongloop


    【解决方案1】:

    您的item 对象可能实现了toJSON function

    打开浏览器的控制台并运行此 sn-p 以查看如何在字符串化 JSON 和实际对象之间产生差异的示例:

    var x = {
    
      name: "foo",
    
      children : function() {
        return [ { name: 'child 1' }, { name: 'child 2' } ];
      },
      
      toJSON: function() {
        var simplified = { name: this.name, children: this.children() };
        
        return simplified
      }
    
    };
    
    // shows children as a simple array
    console.log( JSON.stringify( x, null, 2 ) );
    // {
    //   "name": "foo",
    //   "children": [
    //     {
    //       "name": "child 1"
    //     },
    //     {
    //       "name": "child 2"
    //     }
    //   ]
    // }
    
    // oops... not what you expected
    console.log( x.children[0].name );
    // Uncaught TypeError: Cannot read property 'name' of undefined

    当然,最简单的解决方法是解析字符串化结果:

    var y = JSON.parse( JSON.stringify( x ) );
    console.log( y.children[0].name );
    

    不过,这是最后一种场景类型的解决方案,因为 JSON.stringify 是一个非常昂贵的函数。

    【讨论】:

    • 您好,非常感谢!那行得通。在找到更有效的解决方案之前,我会将其用作临时解决方法。
    • @valvince 你找到更好的解决方案了吗?
    猜你喜欢
    • 2020-02-13
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-16
    相关资源
    最近更新 更多