Doing some practice runs on codecademy, and came across the following problem:
I am able to only console.log "Steve Jobs" and all his info, but I want to also
include "Bill Gates." If anyone knows how to do this that would be great, or
any alternatives to the following code:
var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "Gates",
number: "(206)555-5555",
address: ['One Microsoft Way', 'Redmond', 'WA', '98052']
};
friends.steve = {
firstName: "Steve",
lastName: "Jobs",
number: "(206)777-7777",
address: ['Apple Rd.', 'Cupertino', 'CA', '90210']
};
var list = function(list) {
for (var dale in friends) {
console.log(dale);
}
}
var search = function(name) {
for (var key in friends) {
if (name === friends[key].firstName) {
console.log(friends[key]);
return friends[key];
}
}
};
OK, so when I run this code, only Steve gets printed. It should also print Bill.
Created a JSBin from your code with the addition that I called list(); right at the end. If you run the code using CMD+Enter you will see that the output is as expected, printing out both bill and steve
Copy/pasted the code in the console and calling:
search('Bill');
Works just fine for me, how are you using this code?
Related
I have a seed file in my project where I store dummy data to use in a mock mongoDB database. I have a "comedians" array full of comedian information and a "users" array full of user information. My relevant code looks like this:
let comedians = [
{
_id: mongoose.Types.ObjectId(),
name: "Jerry Seinfeld",
description: "Jerry Seinfeld is best known for playing a semi-fictionalized version of himself in the sitcom Seinfeld. As a standup, Seinfeld specializes in observational comedy and is revered as one of the best known and critically acclaimed comedians of his generation.",
specials: [
{
specialTitle: "I'm Telling You for the Last Time",
specialDescription: "Months after his classic TV sitcom ends, the legendary comic returns to his stand-up roots to deliver his best jokes on a sold-out international tour.",
specialRatings: [
{
userId: users[0]._id,
rating: 2
},
{
userId: users[1]._id,
rating: 5
}
],
},
],
comments: [
{
commentAuthor: "Julia Smith",
commentDate: "October 7th, 2020 at 2:30pm",
commentContent: "I Love This!",
commentLikes: [
users[0]._id,
users[1]._id,
users[2]._id
]
}
],
metrics: {
favoritesReceived: [
users[0]._id,
users[1]._id,
users[2]._id,
users[3]._id,
users[4]._id
],
views: 300
}
}
];
let users = [
{
_id: mongoose.Types.ObjectId(),
username: "userOne",
password: "userOnePassword",
favorited: [
comedians[0]._id,
comedians[1]._id,
comedians[5]._id
],
recentlyViewed: [
comedians[6]._id,
comedians[7]._id,
comedians[9]._id,
comedians[10]._id
],
}
]
The problem is that every time I try to run the test, I get an error saying that "users" is undefined. I understand that this is because I try to access it in the comedians array before it is initialized, but I can't simply move the users array to come before the comedians array, because then I'll be trying to access the comedians array before it's initialized. I'm not sure how to get around this, any suggestions?
You're still in the process of declaring the variables in your object, to prevent this; create a blank object and populate it and/or set undefined/null and add to them later.
//let fun = {
// "user":2,
// "wontwork":fun.user // this will equal undefined and throw errors but looks clever right?
//}
// Let's try the following:
let fun ={};
fun.test = "hellow world";
console.log(fun.test);
fun.tester = function() {
console.log("wow");
};
fun.tester();
let anotherway = {
"test":undefined,
"name":undefined,
"age": 20
};
console.log(anotherway.test);
anotherway.test = "1";
anotherway.test = "2";
anotherway.test = "3";
// Now equals 3
console.log(anotherway.test);
anotherway.test = () => console.warn("don't be alarmed with this warning");
console.log(anotherway.test);
anotherway.test();
let fun = {"user":2,"wontwork":fun.user};
// I can access the AccountSite property from other handlers/functions in the file using loops except in that function. I can get all Other properties using loops in the function except that one.
// I have tried My code in visual studio using console.log for debugging instead of Say(in Alexa) and I can have access to the property with the exact code except for that change.
const Data = [{
AccountName: "Jhon Doe ",
Phone: "353262",
Website: "something.com",
AccountSite: "Random Name",
Description: "Random Description",
AccountOwner: "Jhondoe#yahoo.com"
},
{
AccountName: "Jane Doe ",
Phone: "353223462",
Website: "something2.com",
AccountSite: "Random Name2",
Description: "Random Description2",
AccountOwner: "Janedoe#yahoo.com"
},{
AccountName: "Susan Doe ",
Phone: "353232462",
Website: "something3.com",
AccountSite: "Random Name3",
Description: "Random Description3",
AccountOwner: "susandoe#yahoo.com"
},
];
const getAccounSite_Handler = {
//handler code
//handler code
//handler code
let say;
Data.map(pos => {
say= ` ${pos.AccountSite}`; //if I put pos.Propertyname it would give me the property for the last object in the array for the other propert name except accountsite
// Account site is accessible in this handler if I don't use a loop
//have tried for loop and map
//have a very similar code for another skill but it is working; it is accessing the properties
//end of the handler
}
When I run Alexa it says "There was a problem with the requested skill's response" when the handler is called
As I understood, you want to make Alexa, to read all AccountSites? The code you have written right now always reassigns say on each loop instance. If you want to build a list of values and store it in variable say your code should look like this:
let say = '';
Data.forEach(pos => {
say += `${pos.AccountSite} `;
});
I tested it using your data and got the result that say is equal to:
"Random Name Random Name2 Random Name3 "
Is this is the result you wanted?
I tried to read sorted data from Cloud Firestore using OrderBy.
And Firestore returned data as Following Order:
AAA
BBB
aaa
bbb
Now, what I want is something like following:
AAA
aaa
BBB
bbb
I want this result only using OrderBy not by manual Sorting.
Is there any way to sort like this in Firestore?
Please provide me a solution for this.
Thanks in Advance.
Sorting and filtering in Cloud Firestore are case sensitive. There is no flag to make the sorting or filtering ignore the case.
The only way to achieve your use-case is to store the field twice.
Let's say your field that stores 'AAA' & 'aaa' is called myData. In your client code you'll need to store a second field called myData_insensitive where you store a case-insensitive copy of the data.
DocA:
-> myData = 'AAA'
-> myData_insensitive = 'AAA'
DocB:
-> myData = 'aaa'
-> myData_insensitive = 'AAA'
DocC:
-> myData = 'BBB'
-> myData_insensitive = 'BBB'
DocD:
-> myData = 'bbb'
-> myData_insensitive = 'BBB'
Now you can query and/or order by myData_insensitive, but display myData.
Two interesting thing about this area is:
With Unicode, removing case is more complex than just 'toLowerCase'
Different human languages will sort the same characters differently
Without creating separate indexes for each collation to solve (2), one implementation approach to deal with (1) is via case folding. If you want to only support modern browser versions, then the following gives you a JavaScript example:
caseFoldNormalize = function (s){
return s.normalize('NFKC').toLowerCase().toUpperCase().toLowerCase()
};
caseFoldDoc = function(doc, field_options) {
// Case fold desired document fields
if (field_options != null) {
for (var field in field_options) {
if (field_options.hasOwnProperty(field)) {
switch(field_options[field]) {
case 'case_fold':
if (doc.hasOwnProperty(field) && Object.prototype.toString.call(doc[field]) === "[object String]") {
doc[field.concat("_insensitive")] = caseFoldNormalize(doc[field])
}
break;
}
}
}
}
return doc;
}
var raw_document = {
name: "Los Angeles",
state: "CA",
country: "USA",
structure: 'Waſſerſchloß',
message: 'quıt quit' // Notice the different i's
};
var field_options = {
name: 'case_fold',
country: 'case_fold',
structure: 'case_fold',
message: 'case_fold'
}
var firestore_document = caseFoldDoc(raw_document, field_options);
db.collection("cities").doc("LA").set(firestore_document).then(function() {
console.log("Document successfully written!");
}).catch(function(error) {
console.error("Error writing document: ", error);
});
This will give you a document in Cloud Firestore with the following fields:
{
"name": "Los Angeles",
"state": "CA",
"country": "USA",
"structure": "Waſſerſchloß",
"message": "quıt quit",
"name_casefold": "los angeles",
"country_casefold": "usa",
"structure_casefold": "wasserschloss",
"message_casefold": "quit quit"
}
To handle older browser, you can see one solution in How do I make toLowerCase() and toUpperCase() consistent across browsers
You could also do it manually after you get your results:
docArray.sort((a, b) => {
if (a.myData.toLowerCase() < b.myData.toLowerCase()) {
return -1;
}
if (a.myData.toLowerCase() > b.myData.toLowerCase()) {
return 1;
}
return 0;
});
It's 2022. Firebase is awesome. Firestore is awesome. You don't need to stop using Firestore because of this limitation. Some things on the noSQL world are made on purpose just to speed up things.
What you can do in cases like this is just to create another property on the document, where you would parse the source value and lowercase it. Then you can use the parsed property to sort/order things.
Example:
interface ICompany {
dateAdded: Date
dateEdited: Date
description: string
id?: string
logo?: string
managers?: ICompanyManager
name: string
nameLowercase: string
website?: string
}
Here if you want to sort companies by name.
What you can do:
query(
companiesCollection,
orderBy('nameLowercase', 'asc'),
)
And when adding/editing:
const company = await addDoc(companiesCollection, {
name: data.name,
nameLowercase: data.name.toLowerCase(),
description: data.description,
website: data.website,
dateAdded: new Date(),
dateEdited: new Date(),
} as ICompany)
Voilà.
Hello my JSON Code looks so:
[
{
name: "Pop",
score: 968
},
{
name: "Rock",
score: 881
},
{
name: "Dance & Electronic",
score: 539
},
And so on...
My problem is that I do not know how to get JSON without JSONObject. I know this question has often been asked. These people do not really help me. Can anyone explain this?
Try This,
try {
JSONArray jsonArray=new JSONArray(jsonStr);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
String name = c.getString("name");
String score = c.getInt("score");
}
} catch (final JSONException e) {
}
That's fine, JSON Array can be extracted without going to JSON object. But for an Android development, it is ideal to use an JSON object with the libraries
I am having trouble with something that should be patently obvious. I cant seem to be able to delete properties of my object in node. This is in coffeescript, but I don't think that is relevant.
console.log doc
delete doc.password
console.log doc
Returns:
{ firstname: 'Andrew',
lastname: 'Plummer',
email: 'andrew#stackoverflow...',
password: 'blahblah',
_id: 5014c0a6af36bdaf03000001,
comments: [],
posts: [] }
{ firstname: 'Andrew',
lastname: 'Plummer',
email: 'andrew#stackoverflow...',
password: 'blahblah',
_id: 5014c0a6af36bdaf03000001,
comments: [],
posts: [] }
For something so seemingly obvious I have actually searched around stackoverflow and googled for about half an hour. Sorry if still i have missed a duplicate.
The answer as given by Frédéric in the comment ( so i cant mark it as true) is that my object needed to be explicitly turned into a new object as it had its delete disabled. This is the case with mongoose ODM models in node.