繁体   English   中英

在javascript中将值从一个字典复制到另一个字典

[英]to copy the values from one dictionary to other dictionary in javascript

以下代码段无法将内容从一个字典复制到另一个字典。 它抛出一个显示“copy.Add不是函数”的类型错误。 有人可以建议将键值对从一个字典复制到另一个字典的方法。

dict = {"Name":"xyz", "3": "39"};
var copy={};
console.log(dict);
for(var key in dict)
{
   copy.Add(key, dict[key]);
}
console.log(copy);

你不需要在copy -variable`上调用add 您可以直接使用索引器,如下所示:

dict = {"Name":"xyz", "3": "39"};
var copy = {};
console.log(dict);
for(var key in dict)
{
    copy[key] = dict[key];
}
console.log(copy);

在Javascript中,使用Object.assign(copy, dict)将内容复制到另一个已存在的字典中(即“就地”副本):

dict = {"Name":"xyz", "3": "39"};
var copy={};
console.log(dict, copy);
Object.assign(copy, dict);
console.log(dict, copy);

在较新的JavaScript版本中,您还可以使用...运算符将dict克隆到新的dict中(此方法创建一个新实例):

var copy = {...dict};

额外:您还可以使用此语法组合(合并)两个词典。 就地:

Object.assign(copy, dict1, dict2);

或者通过创建一个新实例:

var copy = {...dict1, ...dict2};

您的代码不是C#代码,正确的方法是,

Dictionary<string, string> dictionary1 =  new Dictionary<string, string>();
Dictionary<string, string> dictionary2 = new Dictionary<string, string>();
dictionary1.Add("Name", "xyz");
dictionary1.Add("3", "39");
foreach(KeyValuePair<string,string> val in dictionary1)
{
  dictionary2.Add(val.Key, val.Value);
}

WORKING FIDDLE

这应该为你做

using System;
using System.Linq;
using System.Collections.Generic;


namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>() { {"Name", "xyz" }, {"3", "39"}};
            Dictionary<string, string> copy = new Dictionary<string, string>();
            dic.Copy(copy);
            copy.ToList().ForEach(c => Console.Write("\n" + c));
            Console.ReadLine();
        }
    }

    public static class Ext
    {
        public static void Copy(this Dictionary<string, string> dic, Dictionary<string, string> other)
        {
            dic.ToList().ForEach(d => other.Add(d.Key, d.Value));
        } 
    }
}

我确定之前已经回答过

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM