1

I have a object habits contain some values

var habits={
       "Drinking":"No",
       "Smoking":"No"
       }

I need to add the values in this variable to another variable in this format

var NewHabits=new Object();
    NewHabits.Drinking="No";
    NewHabits.Smoking="No";

My habits variable is big so i decided to add values using jquery $.each() function

var NewHabits=new Object();
  $.each(habits,function(index, value)
{
 NewHabits.index=value;
 }

But after executing this code i am getting value in NewHabits variable as below

 "index":"No","index":"No"

the problem is giving variable like this NewHabits.index
Please help me to solve this

  • possible duplicate of [How do I add a property to a Javascript Object using a variable as the name?](http://stackoverflow.com/questions/695050/how-do-i-add-a-property-to-a-javascript-object-using-a-variable-as-the-name) – Kristoffer Sall-Storgaard Oct 02 '13 at 07:13

1 Answers1

0

You need to use bracket notation instead of dot notation as the member operator

var NewHabits = {};
$.each(habits, function (key, value) {
    NewHabits[key] = value;
})

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531