Question

I'm building an object in javascript to store data dynamically.

Here is my code :

var id=0;
function(pName, pPrice) {
    var name = pName;
    var price = pPrice;
    var myObj = {
        id:{
            'name':name,
            'price':price
        },
    };
    (id++); // 
    console.log(myObj.id.name); // Acessing specific data
}

I want my id field to be defined by the id variable value so it would create a new field each time my function is called. But I don't find any solution to concatenate both.

Thanks

Was it helpful?

Solution

You can create and access dynamicly named fields using the square bracket syntax:

var myObj = {};
myObj['id_'+id] = {
  'name':name,
  'price':price
}

OTHER TIPS

Is this what you want ?

var myObj = {};
myObj[id] = {
     'name':name,
     'price':price
};

console.log(myObj[id]name); // Acessing specific data

You can use [] to define the dynamic property for particular object(myObj), something like

var myObj = {};
myObj[id] = {'nom':nom, 'prix':prix};

Example

function userDetail(id, nom, prix) {
    var myObj = {};
    myObj[id] = {'nom':nom, 'prix':prix};
    return myObj;   
}

var objA = userDetail('id1', 'sam', 2000);
var objB = userDetail('id2', 'ram', 12000);
var objC = userDetail('id3', 'honk', 22000);

console.log(objA.id1.nom); // prints sam
console.log(objB.id2.nom); // prints ram
console.log(objC.id3.prix);// prints 22000

[DEMO]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top