简体   繁体   中英

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". 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`. 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):

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):

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,

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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