2

Actually I am new to JavaScript, How to create JavaScript object with key and value pair dynamically? I want to create JavaScript object dynamically as mentioned below :-

var Categories = {

Education: {

    name: 'Education',
    models: ['Engineering', 'Arts', 'B.com'],

},

Medical: {

    name: 'Medical',
    models: ['Radiologist', 'Surgeon', 'Neurologist'],

},

Agriculture: {

    name: 'Agriculture',
    models: [ ' Domesticated', 'Bee keep', 'Live stock ‎', 'Orchards ‎', 
'Organic farming ‎'],

   },
};
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Vinit Mehta
  • 449
  • 4
  • 13
  • [this might help.](http://stackoverflow.com/questions/19837916/creating-object-with-dynamic-keys) – Kevin Kloet Nov 21 '16 at 07:35
  • Where does the dynamic key/value come in? What have you tried? Have you looked at [computed properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names) – Patrick Evans Nov 21 '16 at 07:36
  • I Am getting values from two tables category and sub-category and want to show like key value pair suppose I have Education category in category table and Engineering', 'Arts', 'B.com' are the sub-category under Education category. – Vinit Mehta Nov 21 '16 at 07:40
  • Take care in spelling JavaScript to avoid collision with Java. – Basil Bourque Sep 26 '19 at 19:23

1 Answers1

3

for creating json you can use two syntax :

Dot syntax:

var obj ={};
obj.someKnowValue = yourThing;

Bracket syntax :

var x = 'someDynamicString';
var obj = {};
obj[x] = yourThing;

So you can achieve it by using 2nd method where you will pass Education and all as variable to be a key.

Dhaval Chaudhary
  • 5,428
  • 2
  • 24
  • 39
  • thanks for your answer , But I need like Education: { name: 'Education', models: ['Engineering', 'Arts', 'B.com'], }, first get Education dynamically then add name and models into particular category. – Vinit Mehta Nov 21 '16 at 07:46
  • `obj.Education.name = "Education"; obj.Education.models = ['Engineering', 'Arts', 'B.com'];` replace the values with your table values. – Kevin Kloet Nov 21 '16 at 08:03