javascript constructor syntax - javascript

I want to create a simple application for managing contacts. I want to be able to add new contacts and delete contacts. So I'm thinking the best approach is to create a contacts constructor so as to be able to create contacts objects with it. I'm planing to use set and get methods with this constructor.
How do I create a contacts constructor with these value in it.
The contact information should be represented as JSON, for example:
{
"id": "0001",
"first_name": "Charles",
"last_name": "Bronson",
"year_of_birth": 1921,
"email": "charles#bronson.com",
"image_url": "http://image.toutlecine.com/photos/b/r/o/bronson-charles-01-g.jpg",
"addresses": {
"address": [
{ "id": "1001", "street_name": "Storgata", "city": "Åhus" },
{ "id": "1003", "street_name": "Lillgata", "city": "Åhus" },
]
},
"phones": [
{ "id": "5001", "type": "mobile", "number": "070112233" },
{ "id": "5002", "type": "home", "number": "046445566"
]
}
is this a correct way to create a constructor of this sort?
function contacts() {
this.id = id;
this.first_name = first_name;
this.last_name = last_name;
this.year_of_birth = year_of_birth;
this.email = email;
this.image_url = image_url;
this.adressess = adress["id", "street_name", "city"];
this.phones = phone["id", "type", "number"];
}
Thanks!!

You have an array of address objects within an addresses object:
addresses.address[0].id is the way to get the id of the first address object in that array.
addresses.address[1].id would get the id of the second address object
and so on...

Related

How to query for an object within an array in mongoose

I'm new to mongoose and I'm having trouble querying for specific objects within an array.
My data model looks like this:
{
"users": [
{
"_id": "61b0d6637e169ddebf72c18a",
"name": "Brian Test",
"email": "briantest#gmail.com",
"password": "xxx",
"accountType": "type1",
"__v": 0,
"title": "title1",
"about": "about1",
"education": [
{
"recordId": 1,
"institution": "institution1",
"title": "title1"
},
{
"recordId": 2,
"institution": "institution2",
"title": "title2"
},
{
"recordId": 3,
"institution": "institution3",
"title": "title3"
}
]
}
]
}
The query I need is to perform a crud on education records. For it I'll have the user ID and the education record ID.
I'm not sure how to nest the education record query within the user query.
I've tried something like this but It's not working.
let user = await User.findOne({_id: req.user.user.id})
let recordToUpdate = await user.education.findOne({recordId: req.body.recordId})
console.log(recordToUpdate)
I'll appreciate if you could give examples for reading, updating and deleting records aswell.
Thanks!

Get data from JSON Object by using path [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 3 years ago.
Suppose I have a JSON Object like this:
var data = {
"name": "abcd",
"age": 21,
"address": {
"streetAddress": "88 8nd Street",
"city": "New York"
},
"phoneNumber": [
{
"type": "home",
"number": "111 111-1111"
},
{
"type": "fax",
"number": "222 222-2222"
}
]
}
and I want to get the information from this json object by using path which is a string, like
var age = 'data/age'; // this path should return age
var cityPath = 'data/address/city'; // this path should return city
var faxNumber = 'data/phoneNumber/1/number'; // this path should return fax number
Is there any way I can get this information from the string path? Currently I am splitting the path by / and then using it like data.age or data.address.city. But this approach is not useful for any array contained in JSON object.
Is there any better and optimal approach in JavaScript for this problem?
This is how you can access the data from the JSON, no need to use paths:
var data = {
"name": "abcd",
"age": 21,
"address": {
"streetAddress": "88 8nd Street",
"city": "New York"
},
"phoneNumber": [
{
"type": "home",
"number": "111 111-1111"
},
{
"type": "fax",
"number": "222 222-2222"
}
]
}
var age = data.age;
var cityPath = data.address.city;
var faxNumber = data.phoneNumber[0].number; // array first item begins with 0
console.log({age, cityPath, faxNumber})
If you really need to use paths for some reason, I suggest using lodash get method https://lodash.com/docs#get

Javascript: indexing and searching

I have a large array of users which are comprised of 3 different user types ("Admin", "Moderator", "User"). Each user will have the following properties: ("name", "companyId", "type").
The first method will take 1 parameter: an array of users and must return a grouped list according to the user property "type".
The second method will take 4 parameters: a grouped list (result from the first method), an array of user types to include in the search, a string representing the user property to filter by and a string representing the value of the user property. This method must return an array of users as per the search parameters.
My method constructions are returning weird results. Could someone help?
let userTypes = ["Admin", "Moderator", "User"]
function orchestrateUsers(users) {
let result = [];
users.forEach(user => {
result.push({
"name": user.name,
"type": user.type
});
});
return result;
}
function searchUsers(orchestratedUsers, userTypes, property, value) {
}
const users= [{
"name": "Joe",
"companyId": "A2100",
"type": "Admin"
},
{
"name": "Jane",
"companyId": "A2100",
"type": "Moderator"
},
{
"name": "Smith",
"companyId": "A2100",
"type": "User"
},
{
"name": "Smith",
"companyId": "A2100",
"type": "User"
},
{
"name": "Rocket",
"companyId": "A3100",
"type": "Admin"
},
{
"name": "Rick",
"companyId": "A3100",
"type": "User"
},
{
"name": "Tim",
"companyId": "A4100",
"type": "Admin"
}
]
console.log(orchestrateUsers(users));
Answering the first question
const users = [{ "name": "Joe", "companyId": "A2100", "type": "Admin" }, { "name": "Jane", "companyId": "A2100", "type": "Moderator" }, { "name": "Smith", "companyId": "A2100", "type": "User" }, { "name": "Smith", "companyId": "A2100", "type": "User" }, { "name": "Rocket", "companyId": "A3100", "type": "Admin" }, { "name": "Rick", "companyId": "A3100", "type": "User" }, { "name": "Tim", "companyId": "A4100", "type": "Admin" } ]
function orchestrateUsers(users) {
let result = {};
users.forEach(user => {
if (result[user.type]) result[user.type].push(user.name);
else result[user.type] = [user.name];
});
return result;
}
console.log(orchestrateUsers(users));
It looks like you want something like lodash. Here's an example using _.groupBy to group users by type & _.filter to filter for admins:
const users = [
{"name": "Joe", "companyId": "A2100", "type": "Admin"},
{"name": "Jane", "companyId": "A2100", "type": "Moderator"},
{"name": "Smith", "companyId": "A2100", "type": "User"},
{"name": "Rick", "companyId": "A3100", "type": "User" }
];
var usersByType = _.groupBy(users, function (user) {
return user.type;
});
console.log(usersByType);
var admins = _.filter(users, function(user) {
return user.type === "Admin";
});
console.log(admins);
console.log(Object.keys(usersByType));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
Run the code snippet to see the console output.
Why Lodash?
Lodash makes JavaScript easier by taking the hassle out of working
with arrays, numbers, objects, strings, etc. Lodash’s modular methods
are great for:
Iterating arrays, objects, & strings
Manipulating & testing values
Creating composite functions

Javascript JSON Variable Parent [duplicate]

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 6 years ago.
I am working on an ionic 1 app, I do not know if there is a way but for example, here, is there a way I can dynamically assign a parent in this object depending on the value of the Variable?
var contact = {
"Name": "John Doe",
"available": true,
Variable: [
{
"Location": "Home",
"Number": "33"
},
{
"Location": "Work",
"Number": "22"
}
]
};
Lets say Variable = "friends" Then
var contact = {
"Name": "John Doe",
"available": true,
"Friends": [
{
"Location": "Home",
"Number": "33"
},
{
"Location": "Work",
"Number": "22"
}
]
};
I know I can use ES6, the Computed Property Names [Variable] but they are not working on older devices. Is there any alternative method?
Just plain old
var contact = {
"Name": "John Doe",
"available": true,
};
contact[Variable] = [
{
"Location": "Home",
"Number": "33"
},
{
"Location": "Work",
"Number": "22"
}
]

Working With Dynamic Multidimensional key-value pairs in JSON

Having a thorny problem and only see similar but also simpler solutions on SO.
Is is possible to generate a dynamic key AND dynamic values using JS/JSON?
For instance, let's say I have JSON like this:
{
"email": "user#someco.com",
"firstname": "Bob",
"lastname": "Smith",
"company": "ACME",
"custom": {
"services": [
{
"name": "svc1",
"desc": "abcdefg",
"selected": "true",
"status": "None"
},
{
"name": "svc2",
"desc": "abcdefg",
"selected": "true",
"status": "None"
},
{
"name": "svc3",
"desc": "abcdefg",
"selected": "false",
"status": "None"
},
{
"name": "svc4",
"desc": "abcdefg",
"selected": "false",
"status": "None"
}
],
"fields": [
{
"name": "Products",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Product1",
"desc": "abcdef"
},
{
"name": "Product2",
"desc": "abcdef"
}
],
"services": [
"svc1",
"svc2",
"svc3"
]
},
{
"name": "Wines",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Wine 1",
"desc": "abcdef"
}
],
"services": [
"svc4"
]
},
{
"name": "Fruits",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Fruit 1",
"desc": "abcdef"
},
{
"name": "Fruit 2",
"desc": "abcdef"
}
],
"services": [
"svc4"
]
}
]
}
};
I need to go into the fields and for each field (products, wines, fruits) see if a given service is contained within so that I can go back and generate a product or wine or fruit for each service that requires it. But I don't want to repeat the services names more than once. The resulting JSON should look something like this:
{"svc1":["Products"], "svc2":["Products"], "svc3":["Products"], "svc4":["Fruits", "Wines"]}
The hope would be that to generate a dynamic list in Angular I can just turn and loop back through this JSON, pulling out the values for each product, fruit, wine, whatever.
I've been trying a lot of nested for loops and the like but whenever I get more than one layer down the dynamism seems to stop. I'm guessing that for this to work I need to move between JS Objects and JSON?
Right now I'm trying something like this, which isn't quite working, stringify or no. And maybe I'm flip-flopping too much between JSON and JS Objects:
var outObj = [];
var fieldItems;
$.each(jsonObj.custom.fields, function(key, item) {
fieldItems = item;
fieldItems.name = item.name;
$.each(fieldItems.services, function(key, item) {
var serviceName = item;
//check to see if the serviceName already exists
if (outObj.indexOf(serviceName) > -1) {
outObj.serviceName.push(fieldItems.name);
} else {
outObj.push(serviceName);
}
});
});
JSON.stringify(outObj);
console.log("outObj " + outObj);
I get "can't read property 'push' of undefined" errors and the like. Seems this should be possible from a single nested loop, but maybe I need to just do two passes? Any other suggestions?
To me it sounds like overcomplicated solution. You can use basic array methods of javascript to filter out required structure. I am not sure what profiling_value in the presented snippet, so I started from the object structure in OP
var desiredResult = jsonObj.custom.services.reduce(function(result, service){
result[service.name] = jsonObj.custom.fields.filter(function(field){
return field.services.indexOf(service.name) >= 0;
}).map(function(field){ return field.name; });
return result;
}, {});
This gives the expected result for mentioned object.
reduce is required to iterate over all services and accumulate result in one object. Then for each service fields are iterated to filter out only those that contain link to this service. And finally list of filtered fields is transformed (map) into list of strings - their names - and inserted into accumulator

Categories

Resources