1

I need to create an object array in javascript with this structure:

    var nodes = {
        '0': { 'label': 'abc' },
        '1': { 'label': 'cdf' },
        '2': { 'label': 'kjh' },
        '3': { 'label': 'wef' },
        '4': { 'label': 'vrg' }
    }; 

I have tried like this but with no success :(

    var nodes = {};
    for (var i = 0; i < 4; i++) {
        nodes[i] = { i: { 'label': 'xpto'+i } };
    }

Any ideas?

Thanks in advance!

4 Answers 4

7
 var nodes = {};
 for (var i = 0; i <= 4; i++) {
    nodes[i] = { 'label': 'xpto'+i };
 }
Sign up to request clarification or add additional context in comments.

Comments

1

this give the actual needed :

var nodes = {};
for (var i = 0; i < 4; i++) {
    nodes[i+""] = { 'label': 'xpto'+i };
}

4 Comments

The +"" is useless.
the +"" turn the key as string instead of int
If you pass something which isn't a string, it's converted to a string first.
@Hacketo, really? just check it)
1

just simple basic label code to create object array

var object = {};  // Object declaration 
var objectArray = [];  // Array declartion 

object = {'id':1 , 'propertyName1': "value1", 'propertyName2': "value2",'propertyName3': "value3"} // assign vlaue into object 

objectArray.push(object); // push object into array 

console.log(objectArray[0]);  

Comments

0

You can't to use variables in object keys..
So you always need provide it in your leftval:

nodes[i] = {'label': 'test'+i};

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.