Isaac Meneses
Isaac Meneses

Reputation: 163

Create JSON dynamically with dynamic keys and values

I am a beginner and am trying to create the following JSON From data extraction of HTML input texts. How can I create and access the following JSON?

{  
  Brazilians**{
    John**{
      old: 18
    }

    Jones**{
      old: 20
    }
  }

  Canadians**{

    Friedman**{
      old: 22
    }

    James**{
      old: 35
    }
  }
}

Note: ** Means it must be a dynamic key.

My HTML code:

<input type="text" id="nacionality">
<input type="text" id="name">
<input type="text" id="old">

The structure I tried to develop in javascript:

obj[nationality] = name[{old : oldValue}];

alert(obj["Brazilians"]["John"].old);

Upvotes: 1

Views: 10019

Answers (4)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48367

You should create a new object with your details.You can create this using Immediately-invoked function expression.

obj[nationality]=(function(){
   var obj1={};
   obj1[name]={
       old:parseInt(old)
   };
   return obj1;
})();

var obj={  
  Brazilians:{
    John:{
      old: 18
    }
    ,
    Jones:{
      old: 20
    }
  }
  ,
  Canadians:{

    Friedman:{
      old: 22
    }
    ,
    James:{
      old: 35
    }
  }
}
function add(){
   var nationality=document.getElementById('nacionality').value;
  var name=document.getElementById('name').value;
  var old=document.getElementById('old').value;
  obj[nationality]=(function(){
      var obj1={};
      obj1[name]={ 
            old:parseInt(old)
      };
      return obj1;
  })();
  console.log(obj);
}
<input type="text" id="nacionality">
<input type="text" id="name">
<input type="text" id="old">
<button onclick="add()">Add</button>

Upvotes: 3

Kurt Van den Branden
Kurt Van den Branden

Reputation: 12943

Your JSON code is wrong, it should be something like:

{
    "Brazilians":[
        John:{ old: 18 },
        Jones:{ old: 20 }
    ],
    "Canadians":[
        Friedman:{ old: 22 },
        James:{ old: 35 }
    ]
}

Upvotes: 1

BCartolo
BCartolo

Reputation: 719

Something like this?

var obj = {};
obj[document.getElementById('nationality').value] = {};
obj[document.getElementById('nationality').value][document.getElementById('name').value] = {
  old: document.getElementById('old').value
};
console.log(obj);
<input type="text" id="nationality" value="Brazilian" />
<input type="text" id="name" value="John" />
<input type="text" id="old" value="18" />

Upvotes: 5

Hajji Tarik
Hajji Tarik

Reputation: 1082

to make dynamical prop in json you [prop]

function dynmObj (a, b){
    var json ={
      [a] : b
    } 
    return json;
}

Upvotes: 0

Related Questions