-1
    var i=0;
    var mainObj={};
    while(i<2){
        var obj={};
        obj.x ="data";
        obj.y= "data";
        mainObj.i=obj
        i=i+1;
    }
    console.log(JSON.stringify(mainObj));

output :- {"j":{"x":"data"."y":"data"}} {"j":{"x":"data"."y":"data"}}

Expected Output : {0:{"x":"data"."y":"data"},1:{"x":"data"."y":"data"}}

how to achieve this expected output i need the same output key should be number either in string format or number format

  • You cannot achieve that output. Keys of objects are always strings or symbols. Even when assigning a number as the key, it's converted to a string. So, you can get `{"0":{"x":"data","y":"data"},"1":{"x":"data","y":"data"}}` . To do that, you need [Add a property to a JavaScript object using a variable as the name?](https://stackoverflow.com/q/695050) – VLAZ Feb 04 '22 at 14:49
  • 1
    [Working with objects - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects) – Andreas Feb 04 '22 at 14:57

1 Answers1

3

Try mainObj[i] = obj instead of mainObj.i = obj to use a computed key.

Marces Engel
  • 685
  • 6
  • 6