Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/464.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将值从json字符串复制到javascript对象_Javascript_Angularjs - Fatal编程技术网

将值从json字符串复制到javascript对象

将值从json字符串复制到javascript对象,javascript,angularjs,Javascript,Angularjs,角延伸 将所有属性从源复制到目标。这不是我想要的,因为我的目标已经创建,我只需要将所有值从json字符串复制到目标javascript对象 应复制的值在源对象和目标对象中具有相同的属性名称 是否存在任何angularJS或javascript预定义函数来执行此任务?您可以在同一个平台上使用angular.copy 工作代码: <div ng-controller="ExampleController"> <form novalidate class="simple-form"&

角延伸

将所有属性从源复制到目标。这不是我想要的,因为我的目标已经创建,我只需要将所有值从json字符串复制到目标javascript对象

应复制的值在源对象和目标对象中具有相同的属性名称


是否存在任何angularJS或javascript预定义函数来执行此任务?

您可以在同一个平台上使用angular.copy

工作代码:

<div ng-controller="ExampleController">
<form novalidate class="simple-form">
Name: <input type="text" ng-model="user.name" /><br />
E-mail: <input type="email" ng-model="user.email" /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
<button ng-click="reset()">RESET</button>
<button ng-click="update(user)">SAVE</button>
</form>
<pre>form = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>
</div>

<script>
 angular.module('copyExample', [])
   .controller('ExampleController', ['$scope', function($scope) {
     $scope.master= {};

     $scope.update = function(user) {
       // Example with 1 argument
       $scope.master= angular.copy(user);
     };

     $scope.reset = function() {
       // Example with 2 arguments
       angular.copy($scope.master, $scope.user);
     };

     $scope.reset();
   }]);
</script>

现在我已经创建了自己的AutoMapper,因为我在google中找不到可用的东西:

将源对象和目标对象传递给变换函数,并从目标对象上可以找到的每个源对象属性复制值:-


Extend应该仍然适用于此。如果您有一个JSON字符串,那么可以执行angular.extendmy_obj、JSON.parsejson_string@Brennan不复制属性吗?线程开启器想要复制值而不是属性,所以我明白了@extend不复制值,而是复制属性及其值。这不是我要的。
'use strict';
angular.module('mymodule').service('AutoMapper', function () {

    this.transform = function (source, target) {
        for (var sourceProperty in source) {
            for(var targetProperty in target)
            {
                if(targetProperty === sourceProperty)
                {
                    target[targetProperty] = source[sourceProperty];
                    break;
                }
            }
        }
    };
});