1

I need to create an object in javascript, similar to the following structure:

{ 
  '1': { 
    'key1-1': 'val1-1',
    'key-1-2': 'val1-2'
  }, 
  '2': { 
    'key1-1': 'val1-1',
    'key1-2': 'val1-2'
  }
}

I tried with Object(); but the key remains the literal name of the variable.

> var myObj = new Object();
> for (var i  = 1; i< 5; i++) {
... myObj.i = {'key1-1': 'val1-1',
.....         'key-1-2': 'val1-2'}
... }
> console.log(myObj)
{ i: { 'key1-1': 'val1-1', 'key-1-2': 'val1-2' } }

Tried converting the variable i to string but still the same.

> for (var i  = 1; i< 5; i++) {
... var iStr = i.toString();
... myObj.iStr = {'key1-1': 'val1-1',
..... 'key-1-2': 'val1-2'}
... }
> console.log(myObj)
{ iStr: { 'key1-1': 'val1-1', 'key-1-2': 'val1-2' } }

How can we create a json Object with numeric string keys like '1', '2', '3' ...

3
  • 3
    Update from myObj.i to myObj[i] Commented Sep 23, 2018 at 9:26
  • The string conversion happens automatically. Even array indexes are strings. You are using the wrong syntax to define the key. Commented Sep 23, 2018 at 9:29
  • 2
    There is no such thing as a json Object. You want an object? Then it's Javascript. You want a string representation of that object? Then it's JSON. Commented Sep 23, 2018 at 9:31

3 Answers 3

1

You can use two nested for loops along with template literals to make it more generic. And use the bracket notation for creating dynamic properties.

let m = 3;
let n =2;

let result = {};

for(let i = 1; i <=m; i++){
  result[i] = {};
  for(let j = 1; j <=n; j++){
      result[i][`key1-${j}`] = `val1-${j}`;
  }
}
console.log(result);

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

Comments

0

Change myObj.istr to myObj[istr]

Comments

0

https://www.w3schools.com/js/js_object_properties.asp

Another option is use :

myObj[istr] = value

Where istr is a string

Comments

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.