Array of objects in js? - javascript

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

Related

Getting the object variable name for the new object

I have an object constructor such as:
function myObjConstr () {
console.log(object_name);
}
I want this results:
var name1 = new myObjConstr(); //print in console log "name1"
var nameff = new myObjConstr(); //print in console log "nameff"
You would need to pass the object name to the constructor:
function myObjConstr (obj_name) {
this.object_name = obj_name;
console.log(this.object_name);
}
var name1 = new myObjConstr("name1");
var nameff = new myObjConstr("nameff");
you can make a function constructor myObjConstr(), thenafter you can make new myObjConstr().
1) function constructor
function myObjConstr (objName) {
this.objName = objName;
}
2) make object of type myObjConstr
var name1 = new myObjConstr("name1");
var name2 = new myObjConstr("name2");
3) if you want to print the value,
console.log(name1.objName)
You can't pass the variable name to the constructor. Instead you can convert an array of names of variables to array of objects
let names = [
'name1',
'nameff'
]
let objects = names.map(name => myObjConstr(name));
function myObjConstr(name){
this.name = name;
console.log(this.name);
}

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');

In JS, how to declare a value for an object and have all parent keys automatically be created?

myObject = {};
myObject.property1 = "123"
Typing myObject.property1 returns 123
mySecondObject = {};
mySecondObject.property1.value.type.price = "456"
returns TypeError: Cannot set property 'value1' of undefined because all or some parent keys haven't been defined yet, so you have to do something like:
mySecondObject = {};
mySecondObject.property1 = {};
mySecondObject.property1.value = {};
mySecondObject.property1.value.type = {};
mySecondObject.property1.value.type.price = "456"
Is there a method in JS that allows you to just declare an object with as many keys as you want and automatically creates all the parent keys? I couldn't find anything in Underscore.
There's no (standard) function for doing this.
An alternate initialiser is this:
var mySecondObject = { property1: { value: { type: { price : "456" } } } };

Javascript: Object attribute declaration from variable

I am aware I can use another object's property as a key to declare a property of the object, like so:
var object1 = {
myAttr: 'myName'
};
var object2 = {};
var object2[object1.myAttr] = 'myValue';
Then we have object2.myName == 'myValue'.
How would I go about doing that directly in the object's declaration? Something like that:
var object1 = {
myAttr: 'myName'
};
var object2 = {
object1.myattr: 'myValue'
};
But that actually works.
You could change your code a bit and do this:
var object1 = {
myAttr: 'myName'
};
var object2 = new function(){
this[object1.myAttr] = 'myValue'
}();
You can evolve this and pass object1 as an attribute to the object2 function and things go on...
You can do using eval function of javascript
var object1 = { myAttr: 'myName' };
eval("var object2 = { "+object1.myAttr+": 'myValue' }");
console.log(object2.myName);

Concatenate object field with variable in 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]

Categories

Resources