0

I'm looking for the best way to create an object like this in javascript:

  values: {
    0: { 0: 0, 1: 0, …, 59: 0 },
    1: { 0: 0, 1: 0, …, 59: 0 },
    …,
    58: { 0: 0, 1: 0, …, 59: 0 },
    59: { 0: 0, 1: 0, …, 59: 0 }
  }
5
  • If everything is 0-based, have you considered nested arrays instead? Commented Dec 11, 2014 at 17:12
  • 2
    I'm looking for... - Yeah, you're probably not going to just find it... You pretty much have to develop it... Commented Dec 11, 2014 at 17:15
  • nested for loops or two loops. First create object, second loop, clone, and insert Commented Dec 11, 2014 at 17:17
  • Sorry, I voted the first one helped me. They are all valid answers for me. Thanks Edit Yeah, probably I should vote yours for clarity Commented Dec 11, 2014 at 17:29
  • I updated my answer to use objects, not arrays. Commented Dec 11, 2014 at 17:34

4 Answers 4

1
var values = {};

for (var i = 0; i < 60; ++i) {
    values[i] = {};
    for (var j = 0; j < 60; ++j)
        values[i][j] = 0;
}

console.log(values);

That what you want?

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

Comments

1

Just for fun: a functional approach:

function range(n, cb) {
   cb = cb || function (v, i) { this[i] = 0; };
   var _ = {};
   Array(n).join()
    .split(',')
    .map( cb, _);
    return _;
}

// create someObj using range
var someObj = range(10, function (v, i) { this[i] = range(10); });

// display someObj
document.querySelector('#result').innerHTML = 
   '<code>'+
   JSON.stringify(someObj)
   .split('},')
   .join('},<br>&nbsp;')  
   + '</code>';
<div id="result"></div>

Comments

0

You can try this:

var values = {}, temp = {}, i;
for (i = 0; i <= 59; i++)
{
    temp[i] = 0;
}
for (i = 0; i <= 59; i++)
{
    values[i] = temp;
}

Link to jsFiddle here.

Comments

0

check this

var obj = {};
var n = 60;
for(var i=0;i<n;i++){
 obj[i] = {}
 for(var j=0;j<n;j++)
   obj[i][j] = 0;
 }

obj is your values

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.