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 ‎'],

   },
};
4
  • this might help. Commented Nov 21, 2016 at 7:35
  • Where does the dynamic key/value come in? What have you tried? Have you looked at computed properties Commented Nov 21, 2016 at 7: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. Commented Nov 21, 2016 at 7:40
  • Take care in spelling JavaScript to avoid collision with Java. Commented Sep 26, 2019 at 19:23

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
obj.Education.name = "Education"; obj.Education.models = ['Engineering', 'Arts', 'B.com']; replace the values with your table values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.