[英]to copy the values from one dictionary to other dictionary in javascript
The following code snippet is unable to copy the contents from one dictionary to other. 以下代码段无法将内容从一个字典复制到另一个字典。 It is throwing a type error showing "copy.Add is not a function". 它抛出一个显示“copy.Add不是函数”的类型错误。 Can someone suggest the ways to copy the key-value pairs from one dictionary to other. 有人可以建议将键值对从一个字典复制到另一个字典的方法。
dict = {"Name":"xyz", "3": "39"};
var copy={};
console.log(dict);
for(var key in dict)
{
copy.Add(key, dict[key]);
}
console.log(copy);
You won´t need to call add
on the copy
-variable`. 你不需要在copy
-variable`上调用add
。 You can directly use the indexer as follows: 您可以直接使用索引器,如下所示:
dict = {"Name":"xyz", "3": "39"};
var copy = {};
console.log(dict);
for(var key in dict)
{
copy[key] = dict[key];
}
console.log(copy);
In Javascript, use Object.assign(copy, dict)
to copy contents into another already existing dictionary (ie "in-place" 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);
In newer JavaScript versions, you can also clone a dict into a new one using the ...
operator (this method creates a new instance): 在较新的JavaScript版本中,您还可以使用...
运算符将dict克隆到新的dict中(此方法创建一个新实例):
var copy = {...dict};
Extra: You can also combine (merge) two dictionaries using this syntax. 额外:您还可以使用此语法组合(合并)两个词典。 Either in-place: 就地:
Object.assign(copy, dict1, dict2);
or by creating a new instance:, 或者通过创建一个新实例:
var copy = {...dict1, ...dict2};
Your code is not a C# code, the correct way would be, 您的代码不是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);
}
This should do it for you 这应该为你做
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));
}
}
}
Im sure this was answered before 我确定之前已经回答过
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.