1

I have this array:

var myArray =  [{'name': 'name1', 'desc': 'desc1'}, {'name':'name2', 'desc':    
               'desc2'},.....];

and i wanted to turn it into objects like this:

var myobject = {
    obj1: {
        name: 'name1',
        desc: 'desc1',
    },
    obj2 = {
        name: 'name2',
        desc: 'desc2'
    },
    .....
}

I want to iterate through myArray and return an object like myobject .

Thanks

5
  • 3
    why not just use the indexer? Commented Jan 6, 2012 at 13:00
  • There is nothing about JSON here. These are regular JavaScript objects/arrays. Commented Jan 6, 2012 at 13:00
  • You showed the solution, so there's a way ;) Explain better you problem, what's the motivation behind it? Commented Jan 6, 2012 at 13:01
  • please explain what you are trying to achieve :) Commented Jan 6, 2012 at 13:03
  • Actualy it has been done already, try console.log(JSON.stringify(myArray['0'])); console.log(JSON.stringify(myArray['1'])); alert('Arrays are Objects too!'); Commented Jan 6, 2012 at 13:13

3 Answers 3

3

Try this:

var myArray =  [{'name': 'name1', 'desc': 'desc1'}, {'name':'name2', 'desc':    
           'desc2'}];

var myObject = {};

for(var i=0;i<myArray.length;i++){
  myObject["obj"+i] = myArray[i];
}
Sign up to request clarification or add additional context in comments.

Comments

1
var i;
for (i = 0; i < myArray.length; ++i) {
  window['json' + (i + 1)] = myArray[i];
}

1 Comment

Note that str + num + num will do concatenation, so it will become json01 etc.
1

Use a loop or just use the array's indexes like so:

var myArray =  [{'name': 'name1', 'desc': 'desc1'}, {'name':'name2', 'desc': 'desc2'}];

var json1 = myArray[0];
var json2 = myArray[1];


console.log( json1.name );

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.