custom javascript objects as properties of other custom javascript objects - javascript

I want to create some custom javascript objects some of which have properties which are other objects. I'm not sure what the syntax would be to do this. My pseudo code is below with the idea that I have a person object and an order object. The order object has a property that I want to be of the person object type. Is this possible in javascript and if so, can someone give me a basic example? Thanks.
var person {
name: "John",
gender: "M",
age: 3
}
var order {
customer: person, /*the property name is customer but of type person - is this possible?*/
total: 100
}

Consider constructors:
function Person( name, gender, age ) {
this.name = name;
this.gender = gender;
this.age = age;
}
function Order( customer, total ) {
this.customer = customer;
this.total = total;
}
Usage:
var person1 = new Person( 'John', 'M', 3 );
var order1 = new Order( person1, 100 );
The constructors act as classes. You invoke them via new to create new instances (persons and orders).

You were almost correct; all you need is to include some '='
var person = {
name: "John",
gender: "M",
age: 3
}
var order = {
customer: person, /*the property name is customer but of type person - is this possible?*/
total: 100
}

You could do this:
var person = {
name: "John",
gender: "M",
age: 3
};
var order = {
customer: person,
total: 100
};
This also passes in JSLint. You were missing '=' signs.

You code is nearly fine (missing the = to assign the anonymous object to the variable):
var person = {
name: "John",
gender: "M",
age: 3
};
var order = {
customer: person, /*the property name is customer but of type person - is this possible?*/
total: 100
};
http://jsfiddle.net/D7u3x/

Sure, thats pretty much it. Your syntax is a little off, but only slightly.
Here is your example: jsfiddle

Related

Shorthand for picking object properties - combine ES6 `Object Deconstruction` with `Object Property Value` shorthand

Following code outputs {name: "Bob", surname: "Smith"} and it works fine. I want to know can I make it shorter.
((person = { name: 'Bob', surname: 'Smith', age: 22, }) => {
const {
name, // (a) create variable from deconstructing
surname,
} = person;
return {
name, // (b) reuse variable as new object parameter name (and value)
surname
}
})();
Can I somehow merge object deconstruction to variables (a) with returning a new object with Object Property Value shorthand (b)?
I use here shorthand but then its purpose is defeated by the need to manually re-use parameters. I want to mention the name or surname word in my function once not twice...
Destructure person in the function's declaration:
const result = (({ name, surname } = { name: 'Bob', surname: 'Smith', age: 22, }) => ({
name, // (b) reuse variable as new object parameter name (and value)
surname
}))();
console.log(result);
You can not mention it at all
((person = { name: 'Bob', surname: 'Smith', age: 22, }) => {
const {age,...ans} = person;
return ans
})()

what is the most terse way to return an array of entities in typescript?

I'm trying to figure out the most terse way to return an array of objects from a ts function. The following function works as expected:
getAuthors1(): Author[]
{
var authors: Author[] =
[
{
FirstName: "John";
MI: "J";
LastName: "Smith";
}
];
return authors;
}
The following function errors out b/c it appears that ts won't let me return an object array directly as opposed to as a variable:
getAuthors2(): Author[]
{
return Author[] =
[
{
FirstName: "John";
MI: "J";
LastName: "Smith";
}
];
}
The following function errors out b/c a value isn't provided for MI:
getAuthors3(): Author[]
{
var authors: Author[] =
[
{
FirstName: "John";
LastName: "Smith";
}
];
return authors;
}
Questions:
Are values required for all object properties when creating an object initialized array?
1a. If this is the case do developers typically initialize property values in the class?
Is there a way to return an object array directly, similar to my getAuthors2() example above, as opposed to having to assign this to a variable and then return the variable?
If you have an interface defined and you create an object where you tell TypeScript that it should be of that type, it will complain for any missing property, as it should.
One way to get around this is to use a mapped type where you state that each property of the object is optional, and use it like Partial< Author >. See the official documentation for more info.
You can return the array right away, just remove the type that you've added after return:
getAuthors2(): Author[] {
return [
{
FirstName: 'John',
MI: 'J',
LastName: 'Smith',
}
];
}
Also wherever possible you should remove the manually defined types, like the return Author[] from your functions. TypeScript will use type inference to figure it out by itself.
In your specific example either you leave the return type defined, and typescript will make the required checks or use something similar to what you have in getAuthors3. If you get or have the objects already typed just place them in the array and TypeScript will do the rest:
getAuthors() {
const author: Author = {
FirstName: 'John',
MI: 'J',
LastName: 'Smith',
};
return [author];
}
Return the array, not the result of an array assignment.
function getAuthors() {
return [{
FirstName: "John",
MI: "J",
LastName: "Smith"
}];
}
console.log(getAuthors());

Insert values in to an object from loop

I'm trying to create a script that will insert some values in to an object.
I basically want to end up with a series of objects that would look something like this -
myObj.data.person[0].name = 'name 1';
myObj.data.person[1].name = 'name 2';
myObj.data.person[2].name = 'name 3';
etc
Here is my object which contains an array of objects.
var addressBook = {
data: [
person = {
name: '',
address: ''
}
]
}
And a for loop to insert repeating information.
for (i=0; i < 10; i++)
{
myObj.data.person[i] = {name: 'Joe Bloggs', address: 'Main Street'};
console.log(myObj.data.person.name);
}
Whenever I run this code I get the following error -
Uncaught TypeError: Cannot set property 'person' of undefined at <anonymous>:14:24
So, the question is where am I going wrong ? And furthermore would this be considered the right way to go about creating a list of Objects (e.g. Person 1, Person 2 etc)?
(I'm ultimately thinking of how I can create something like a Person constructor and use a loop to create multiple Person objects).
Thanks,
Please try to change your object notation in following way
var addressBook = {
data: [{
name: '',
address: ''
},
{
name: 'Roshan',
address: ''
},
{
name: 'Roshan1',
address: ''
}
]
}
try this :
myObj.data[i].person = 'John';
myObj.data[i].address = 'NYC';
See this Answer as addendum to isetty ravitejakumar's Answer
You should consider writing a prototype / class for your usecase.
In this case you could keep better track of your data.
maybe something like this:
var AddressBook = {},
Person = {};
(function() {
AddressBook.prototype = {
data: [],
add: function(person) {
this.data.push(person);
}
};
Person = function(name, address) {
this.name = name;
this.address = address;
}
Person.prototype = {
name,
address
};
})();

Javascript - how to capitalize key.value within an object?

How do I capitalize the first letter of each contact's first name?
String.prototype.capitalize = function (string) { return string.charAt(0).toUpperCase() + string.slice(1);}
var contactList = {};
contactList.bobSmith = {
firstName: "bob",
lastName: "smith",
location: "new york"
};
contactList.johnDoe = {
firstName: "john",
lastName: "doe",
location: "san francisco"
};
var contact2 = contactList["johnDoe"].firstName;
contact1.capitalize();
contact2.capitalize();
console.log(contact1 + " " + contact2);
I get an error message that says "Uncaught TypeError: Cannot read property 'charAt' of undefined".
function () { return this.charAt(0).toUpperCase() + this.slice(1);}
Your String.prototype.capitalize function requires an argument string which you're not passing to it when called. I'd recommend avoiding adding methods to the String.prototype and just use a stand-alone function instead...
function capitalise(str) {
return str.slice(0,1).toUpperCase() + str.slice(1);
}
contact2 = capitalise(contact2);
//=> "John"
...or if you're looking to capitalise the value in the contactList object, then just...
contactList.johnDoe.firstName = capitalise(contact2);
Hope that helped. :)
I wouldn't make it a habit of popping methods into prototype. It's frowned upon because future versions of JavaScript could come out and put a method with the same name in the prototype and you would be screwed.
I didn't write it this way but you could put the capitalize function on to the contactList object and you would basically achieve the same thing your trying to do with the prototype.
var contactList = {};
contactList.names =[
{
firstName: "bob",
lastName: "smith",
location: "new york"
},
{
firstName: "john",
lastName: "doe",
location: "san francisco"
}];
function capitalizeName(name) {
var strCap = name[0].toUpperCase();
var tailTxt = name.substr(1, name.length);
fullTxt = strCap + tailTxt;
return fullTxt;
)
$.each( contactList.names, function(i){
capitalizeName(contactList.names[i].firstName);
});

Adding objects into an array

Hello I am very new to JavaScript and need some guidance. I am trying to build a reference for people in a club. I started by creating an array like so:
var People = ['Adam', 'Bruce', 'Steve']
But now I want to add characteristics to Adam, for instance height, weight, age, etc.
I want to be able to access information regarding people in my array by something like:
alert(People.Adam.height);
How would I structure it so that objects in my array has unique characteristics?
var people = [],
adam = {
height: 200,
weight: 200,
age: 20
};
people.push(adam);
console.log(people[0].height); // 200
or use object instead of array:
var people = {},
adam = {
height: 200,
weight: 200,
age: 20
};
people.adam = adam;
console.log(people.adam.height); // 200
You're currently adding strings into your array, not objects. You need to make your people into objects.
var adam = {
name: 'Adam',
height: 6.0
}
To retrieve Adam's height now, you'd call adam.height. So if you had an array, People, with adam (and others) inside, here's how you could do it:
var people = [adam]
alert(people[0].height)
// Alerts 6
Edit: alternatively, if you'd like to access Adam by name, you could make people an object instead of an array:
var people = {'adam' : adam}
alert(people.adam.height)
// Alerts 6
You can create an object, so you can access any nested property of that object:
var People = {
Adam: {
height: '187',
age: '22',
favorite_color: 'orange'
},
Paul: {
height: '156',
age: '38',
favorite_color: 'blue'
},
}
You need to make an object that have name of the people as key and the value for each key would be details for the person in form of an object. It could be something like
var People = {
"Adam" : {
"height" : "someValue",
"anotherParam" : "someOtherValue"
},
"Bruce" : {
"height" : "someValue",
"anotherParam" : "someOtherValue"
}
}
Use a class. It might look like this:
class Person {
constructor(height, weight, birth_year) {
this.height = height;
this.weight = weight;
this.birth_year = birth_year;
}
}

Categories