2

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

3 Answers 3

2

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

var myObj = {};
myObj['id_'+id] = {
  'name':name,
  'price':price
}
Sign up to request clarification or add additional context in comments.

Comments

0

Is this what you want ?

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

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

Comments

0

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]

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.