【问题标题】:how to concat two json objects in angularJs如何在angularJs中连接两个json对象
【发布时间】:2017-09-14 19:15:08
【问题描述】:

我在角度控制器中有以下内容:

var jsonOne = $cookies.get('test');
// console logs {"domain":"localhost","zip":33333}

var jsonTwo = angular.toJson($scope.formData);
// console logs {"id":"210","name":"sam"}

var final = $.extend(jsonOne, jsonTwo);
// console logs [object object]

我的目标是:

var final
// console logs {"domain":"localhost","zip":33333, "id":"210","name":"sam"}

我在 Angular 下询问是因为当我在静态 html 文档中尝试它时它工作正常,但由于某种原因它不会在 Angular 中工作。有什么想法吗?

【问题讨论】:

  • 定义“不起作用”。什么是代码,什么是输入,什么是预期输出,什么是实际输出(或错误)?
  • 预期结果是它记录 {"domain":"localhost","zip":33333, "id":"210","name":"sam"},而不是它日志[对象对象]
  • 您回答了 4 个问题中的 1 个。回答其他3个。您没有发布任何记录任何内容的代码。
  • jsonOne 和 jsonTwo 不是对象。它们是字符串。 angular.toJson() 接受一个对象并将其转换为 JSON 字符串。

标签: angularjs json object


【解决方案1】:

问题似乎是您使用了angular.toJson,from the docs 将输入序列化为 JSON 字符串。使用带有angular.extend() 的字符串将无法正常工作。

尝试检索您的元素而不将它们序列化为字符串 - 似乎您可能已经拥有这些对象并且不需要使用 .toJson。

获得两个对象后,使用angular.extend() 将它们组合起来。

var first = { "A": "B" };
var second = { "C": "D" };

var third = angular.extend(first, second);

console.log(third);
// in chrome it logs { A: "B", C: "D" }

【讨论】:

    猜你喜欢
    • 2019-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-24
    • 2017-09-26
    • 2016-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多