Concatenate object field with variable in javascript - javascript

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

You can create and access dynamicly named fields using the square bracket syntax:
var myObj = {};
myObj['id_'+id] = {
'name':name,
'price':price
}

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]

Related

Real use case dynamic (computed) property

A dynamic property:
var obj = {
// Computed (dynamic) property names
[ 'prop_' + (() => 42)() ]: 42
};
This is of course very fancy. But where could someone use this without adding unnecessary complexity?
If you have a property name as a constant:
var obj = { [SOME_CONSTANT]: 42 };
One case where I wanted it was where property names for JSON were defined in generated files, based off Java classes.
// Generated
var SomeJsonBodyParams = {NAME: 'name', ID: 'id', ETA, 'estimatedTimeOfArrival'};
// Using it
sendAjax('some/url', {
[SomeJsonBodyParams.NAME] = userData.name,
...
});
We even had a method so we could kind of do it
function makeObj() {
var obj = {};
for (var i=0; i < arguments.length; i+=2) {
obj[i] = obj[i+i];
}
return obj;
}
sendAjax('some/url', makeObj(
SomeJsonBodyParams.NAME, userData.name,
...
));
You can use it in class and with Symbols:
class MyClass {
[Symbol.iterator]() {
// my iterator
}
}
Let's say you have:
var hi = 'hi';
var test = 'test';
var hello = 'hello';
Instead of:
var object = {};
object[hi] = 111;
object[test] = 222;
object[hello] = 333;
You could write it in a much shorter syntax:
var object = {
[hi]: 111,
[test]: 222,
[hello]: 333
}
E.g. it could be used when you want to use a, let's say, constant as a key in object.
const DATA_TYPE = {
PERSON: 'person',
COMPANY: 'company'
};
let cache = {
[DATA_TYPE.PERSON]: getPerson()
};
And later access:
cache[DATA_TYPE.PERSON]
Instead of DATA_TYPE.PERSON could be anything (including some real-time calculated values).

Parameter name in object when its created

I want to get parameter name when a function applied as new. I have search but i couldn't find what i am exactly looking.
Here is a sample;
var myobject = function(){
/*I need "param" in here as string*/
}
var param = new myobject();
thanks for any idea or referance without any library.
the original case code is:
var selectQueue = [];
var queue = function(data){
this.defaults = {
name: "base",
type: "fifo"
}
this.availableTypes = ["fifo","lifo","random"];
if(!data){data = {};}
for(param in this.defaults){
if(!data[param]){
data[param] = this.defaults[param];
}
}
/*this is what i want to do with dynamic name*/
selectQueue.push({
a:this
});
}
var a = new queue();
What you want is not really possible in JS, but a possible workaround is to send the name you want to the constructor, such as:
var selectQueue = [];
var queue = function(data, name){
this.defaults = {
name: "base",
type: "fifo"
}
this.availableTypes = ["fifo","lifo","random"];
if(!data){data = {};}
for(param in this.defaults){
if(!data[param]){
data[param] = this.defaults[param];
}
}
var o = {};
o[name] = this;
selectQueue.push(o);
}
var a = new queue(data, 'a');
Another possibility is to keep track of the current index of selectQueue.
The object has properties and this is the syntax.
var myObject = function(){
name: "your name",
age: 19,
hobby: "football"
}
var param = myObject.name;
That is the way you define a property.

Adding protos but keeping object structure, javascript

Lets say I get this from an API:
var _persons = [
{
name: 'John'
},
{
name: 'Sarah'
}
];
Now I want to add a greeting function. I want to save memoryspace so I create a Person 'class' and add the function as a proto.
function Person(person){
this.person = person;
}
Person.prototype.greeting = function(){
return 'hello ' + this.person.name
};
I instantiate each person:
var persons = [];
function createPersons(people){
for(var i = 0;i<people.length;i++){
var person = new Person(people[i]);
persons.push(person);
}
};
createPersons(_persons);
Problem is this:
console.log(persons[0].name) //undefined
console.log(persons[0].person.name) //'John'
Is there anyway I can get the first console.log to work?
https://jsbin.com/zoqeyenopi/edit?js,console
To avoid the .person appearing in the object you need to copy each property of the source plain object directly into the Person object:
function Person(p) {
this.name = p.name;
...
}
[or use a loop if there's a large number of keys]
You've then got a mismatch between the named parameter and the variable you're iterating over in the createPersons function. Additionally it would make more sense to have that function return the list, not set an externally scoped variable:
function createPersons(people) {
return people.map(function(p) {
return new Person(p);
});
}
var persons = createPersons(_persons);
NB: the above uses Array.prototype.map which is the canonical function for generating a new array from a source array via a callback.
Loop over all the keys in your object argument and assign them to this
function Person(person){
for (var key in person) {
this[key] = person[key];
}
}
var persons = [];
function createPersons(people){
for(var i = 0;i<people.length;i++){
var person = new Person(people[i]);
persons.push(person);
}
};
createPersons(_persons);
Should be using people as a variable
You're creating a Person object that is given a variable person. You need to change the value you're getting by replacing
var person = new Person(people[i]);
with
var person = new Person(people[i]).person;
var _persons = [
{
name: 'John'
},
{
name: 'Sarah'
}
];
function Person(person){
this.person = person;
}
Person.prototype.greeting = function(){
return 'hello ' + this.person.name;
};
var persons = [];
function createPersons(people){
for(var i = 0;i<people.length;i++){
var person = new Person(people[i]).person;
persons.push(person);
}
};
createPersons(_persons);
console.log(persons[0].name); // logs 'John'
document.write('John');

Set a property as reference to an object

I have a table that have a property named "recordsource" that will hold the name of the object that will fill the content of the table.
<table id="tbl" recordsource="myobj">
Now here are my functions:
var myobj;
function obj()
{
this.code = new Array();
this.name = new Array();
}
myobj = new obj();
myobj.code = ["a","b","c"];
myobj.name = ["apple","banana","carrot"];
function populate_table()
{
mytable = document.getElementById("tbl");
mytableobj = mytable.getAttribute("recordsource"); //this will return a string
//my problem is how to reference the recordsource to the myobj object that have
//the a,b,c array
}
try this window[ mytableobj ] it will return myobj
One way is to use an object as a list of all the other objects that you want to be able to access.
...
var obj_list = {
'myobj': myobj
};
function populate_table()
{
mytable = document.getElementById("tbl");
mytableobj = mytable.getAttribute("recordsource");
// Then obj_list[mytableobj] == myobj
obj_list[mytableobj].code[0] // Gives "a"
obj_list[mytableobj].name[0] // Gives "apple"
}

Array of objects in js?

It's a silly question, but is this an array of objects in js?
var test =
{
Name: "John",
City: "Chicago",
Married: false
}
if so, how do I declare a new one.. I dont think
var test = new Object();
or
var test = {};
is the same as my example above.
No.
That's an object with three properties.
The object literal is just a shortcut for creating an empty object and assigning properties:
var test = { }; //or new Object()
test.name = "John";
test.city = "Chicago"
test.married = false;
An array of objects would be
myArray = [
{ prop1 : "val1", prop2 : "val2" },
{ prop1 : "A value", prop2 : "Another value" }
]
You would access the first object's prop2 property like this
myArray[0].prop2
"if so, how do I declare a new one?"
To do what I think you want you would have to create an object like this
var test = function() {
this.name = "John";
this.city = "Chicago";
this.married = false;
}
var test2 = new test();
You could alter the properties like this
test2.name = "Steve";
You can create an array of your objects like this
myArray = [test, test2];
myArray[1].married = true;
No, it's an object.
You could create an array of objects like this:
var array_of_objects = [{}, {}, {}];
For creating new objects or arrays I would recommend this syntax:
var myArray = [];
var myObject = {};
No, test is an object. You can refer to it's instance variables like so:
var myname = test.Name;
It is an object, but you must also understand that arrays are also objects in javascript. You can instantiate a new array via my_arr = new Array(); or my_arr = []; just as you can instantiate an empty object via my_obj = new Object(); or my_obj = {};.
Example:
var test = [];
test['name'] = 'John';
test['city'] = 'Chicago';
test['married'] = false;
test.push('foobar');
alert(test.city); // Chicago
alert(test[0]); // foobar

Categories

Resources