new to Javascript. Attempting to pull data from a weather API for a project but have run into an issue that I'm sure is simple to solve. Here is the data I've fetched already:
{coord: {…}, weather: Array(1), base: "stations", main: {…}, visibility: 9656, …}
coord: {lon: -76.13, lat: 43.04}
weather: Array(1)
0: {id: 500, main: "Rain", description: "light rain", icon: "10d"}
length: 1
__proto__: Array(0)
base: "stations"
main: {temp: 281.12, feels_like: 274.24, temp_min: 280.37, temp_max: 282.04, pressure: 1004, …}
visibility: 9656
wind: {speed: 8.2, deg: 310}
rain: {1h: 0.25}
clouds: {all: 90}
dt: 1587324361
sys: {type: 1, id: 5965, country: "US", sunrise: 1587291309, sunset: 1587340289}
timezone: -14400
id: 0
name: "Syracuse"
cod: 200
__proto__: Object
What I need to do is select "Rain" under the weather class. However, since it is inside of an array I do not know how to get it. For example, if I do
data.visibility
I will of course be returned with 9656. Yet if I do
data.weather.0 or even data.weather.["0"]
I will be met with the following error: Uncaught SyntaxError: Unexpected number. And even if I were to not get this error, how would I go about accessing the specific element "Rain" in the Array?
Sorry if this is an easy fix, just having trouble finding an answer due to the very specific wording whenever I search.
If you need only the first element of an array, you can simply use an index to get the value data.weather[0].main.
Or you can map an array via the Array method data.weather.map(item => item.main). You will get a customized array ["Rain"]
You access it like this:
data.weather[0].main
where 0 is an integer describing the index of the element of the array.
Related
I am working with an api called spoonacular.
I search some ingredients and I'm returned an array of objects containing recipes.
I would like to take a variable (the recipe title) from each object and input them into the inner HTML wrapped in and tags.
The array of objects returned is something like this (this is simplified)
0
:
{id: 661447, title: 'Square Deviled Eggs', image: 'https://spoonacular.com/recipeImages/661447-312x231.jpg', imageType: 'jpg', usedIngredientCount: 2, …}
1
:
{id: 638035, title: 'Chicken Cordon Bleu', image: 'https://spoonacular.com/recipeImages/638035-312x231.jpg', imageType: 'jpg', usedIngredientCount: 2, …}
2
:
{id: 641896, title: 'Easy Chicken Cordon Bleu', image: 'https://spoonacular.com/recipeImages/641896-312x231.jpg', imageType: 'jpg', usedIngredientCount: 2, …}
3
:
{id: 652359, title: 'Monte Carlo Sandwich', image: 'https://spoonacular.com/recipeImages/652359-312x231.jpg', imageType: 'jpg', usedIngredientCount: 2, …}
4
:
{id: 663641, title: 'Tomato tarte tatin', image: 'https://spoonacular.com/recipeImages/663641-312x231.jpg', imageType: 'jpg', usedIngredientCount: 2, …}
I currently have the titles input into the page with tags using this code where data is the array of objects:
let recipeTitles = function(){
return data.map(el => el.title).join('</br>')
}
document.querySelector('#recipeTitle').innerHTML = recipeTitles()
I thought maybe something like
return data.map(el => <p>${el.title}</p>).join('')
or
return data.map(el => `<p>`${el.title}`</p>`).join('')
Might work, but that is incorrect syntax I think now.
So i can't figure out how to do it.
I haven't tried to input links into the anchor tags yet because I haven't figured out how to add the anchor tags, but I think that part won't be too difficult using the map function?
You're almost there
return data.map(el => `<p>`${el.title}`</p>`).join('')
Is incorrect syntax, but:
return data.map(el => `<p>${el.title}</p>`).join('')
Is not.
Changing a deeper property of an object shows in console but not when we open it or access it later.The below is my object :
section#shikhar:
1: {displayName: "Entity", dropdownType: "SINGLESELECT", fieldType: "DROPDOWN", values: Array(24), template: null, …}
2:
customTooltip: null
defaultValue: null
dependentValues: {AVS - Avionics: Array(4), DMS - Defence Mission Systems: Array(4), LAS - Land and Air Systems: Array(5), SIX - Secure Communications & Information Systems: Array(4), GTS - Ground Transportation Systems: Array(4), …}
displayName: "Business Line"
dropdownType: "SINGLESELECT"
fieldType: "DROPDOWN"
isDashboard: true
isOptional: false
isParentOf: "3"
isReporting: true
isTooltipEnabled: null
parent: 1
parentValue: ["depend"]
productTooltip: null
sequenceNumber: 2
template: null
values: []
__proto__: Object
3: {displayName: "Product Line Family", dropdownType: "SINGLESELECT", fieldType: "DROPDOWN", values: Array(0), template: null, …}
4: {displayName: "Product Line", dropdownType: "SINGLESELECT", fieldType: "DROPDOWN", values: Array(0), template: null, …}
5: {displayName: "Brief Instructions", dropdownType: null, fieldType: "TEXT", values: null, template: null, …}
6: {displayName: "Main message", dropdownType: null, fieldType: "TEXT", values: null, template: null, …}
7: {displayName: "Tone of voice", dropdownType: "MULTISELECT", fieldType: "DROPDOWN", values: Array(10), template: null, …}
8: {displayName: "Audience to address (Primary)", dropdownType: "MULTISELECT", fieldType: "DROPDOWN", values: Array(2), template: null, …}
9: {displayName: "Target to reach (Secondary)", dropdownType: "MULTISELECT", fieldType: "DROPDOWN", values: Array(9), template: null, …}
10: {displayName: "Sub-type", dropdownType: "SINGLESELECT", fieldType: "DROPDOWN", values: Array(2), template: null, …}
11: {displayName: "Size", dropdownType: "SINGLESELECT", fieldType: "DROPDOWN", values: Array(0), template: null, …}
12: {displayName: "Custom Size", dropdownType: null, fieldType: "TEXT", values: Array(0), template: null, …}
13: {displayName: "Copyrights: Expiry Date", dropdownType: null, fieldType: "DATE", values: null, template: null, …}
14: {displayName: "Output Format", dropdownType: "SINGLESELECT", fieldType: "DROPDOWN", values: Array(4), template: null, …}
15: {displayName: "Other", dropdownType: null, fieldType: "TEXT", values: Array(0), template: null, …}
16: {displayName: "Tags", dropdownType: null, fieldType: "TEXT", values: null, template: null, …}
Here the problem is that even though I am setting the values inside the "2" object it still shows it as [] but actually it should have 4 values like :
{displayName: "Business Line", dropdownType: "SINGLESELECT", fieldType: "DROPDOWN", values: Array(4), template: null, …
I know the object is getting mutated somehow because even the console says that the value was evaluated just now.
The code I am using being :
updateAllCommonValues=(val,id)=>{
const { commonTemplateFields } = this.state;
var commonTemplateValues = JSON.parse(JSON.stringify(commonTemplateFields));
_.forEach(commonTemplateValues,(section,k)=>{
_.forEach(section,(field,key)=>{
if(key == id){
field.value = val
if(field.isParentOf != null){
commonTemplateValues[k][Number(field.isParentOf)]['values'] = section[field.isParentOf].dependentValues[val];
}
}
})
})
this.setState({
commonTemplateFields:commonTemplateValues
},()=>{
this.props.updateFinalPojo('orderInfo',commonTemplateValues);
})
}
The correct value of commonTemplateFields is not coming to setstate i.e. the array for values instead it is empty as the initial state.
PS: It passes all if conditions.
PPS : Object structure :
{
"values":[
"Flight Avionics (FLX)",
"In-Flight Entertainment (IFE)",
"Training & Simulation (T&S)",
"Microwave & Imaging (MIS)"
],
"parent":1,
"parentValue":[
"depend"
],
"dependentValues":{
"AVS - Avionics":[
"Flight Avionics (FLX)",
"In-Flight Entertainment (IFE)",
"Training & Simulation (T&S)",
"Microwave & Imaging (MIS)"
],
"DMS - Defence Mission Systems":[
"Above Water Systems (AWS)",
"Electronic Combat Systems (ECS)",
"Intelligence Surveillance & Reconnaissance (ISR)",
"Under Water Systems (UWS)"
],
},
"isParentOf":"3"
}
There isn't enough in your question to know the structure of what you're updating precisely, but in general, JSON.parse(JSON.stringify(...)) is a lossy way to clone objects (also slow, as it makes a trip through JSON). There's also no need to clone the entire structure, just the parts you're changing.
Separately, any time you're setting state based on existing state, you must use the callback version of setState, because state updates are asynchronous so if you don't use the callback version, you could be using stale source state information.
If I'm reading your code correctly, commonTemplateFields is either an array or an object containing sections, which are either arrays or objects containing fields, which are objects. So here's how you would update the field(s) whose field key is id (see comments):
updateAllCommonValues = (val,id) => {
// Must use callback version of `setState`
this.setState(
({commonTemplateFields}) => {
// Get a shallow copy of `commonTemplateFields`
commonTemplateFields = {...commonTemplateFields}; // Or `= [...commonTemplateFields]` if it's an array
// Loop through the sections and their fields
_.forEach(commonTemplateFields, (section, sectionKey) => {
_.forEach(section, (field, fieldKey) => {
if (fieldKey == id) {
// Need to update this field, shallow copy the section
section = commonTemplateFields[sectionKey] = {...section}; // Or = `[...section]`, I can't tell whether section is an object or array
// Shallow copy and update the field
field = section[fieldKey] = {...field, value: val};
if (field.isParentOf != null) {
// Shallow copy and update the dependent field
const index = Number(field.isParentOf);
section[index] = {...section[index], values: section[index].dependentValues[val]};
}
}
});
});
// Return the update
return {commonTemplateFields};
},
() => {
this.props.updateFinalPojo('orderInfo', this.state.commonTemplateFields);
}
);
}
Hopefully, between the JSON thing and the async thing, that helps sort out the issue.
Side note: FWIW, in modern JavaScript there's no need for _.forEach, and using _.forEach can make the code less readable by hiding the structure of your data. If you're looping through an array, you can use the built-in forEach or a for-of loop as appropriate (the for-of might be on the array itself, or on the result of calling its entries method if you need both value and index). If you're looping through the contents of an object, you can use for-of loop on Object.keys, Object.values, or Object.entries depending on what you're doing.
Obviously, though, if you simply prefer _.forEach, that's a style choice you're entirely entitled to make. :-)
I figured out the solution to this and posting this as it might be helpful to someone else as well. When we do looping over nested object it appears as if the comparision is made only on the first level. The property I was changing was at 3rd level. Maybe I am wrong but this is the conclusion I have arrived on coz when I made another change at the first level, the value change at 3rd level started to show as well.
This question already has answers here:
MongoDB: How to update multiple documents with a single command?
(13 answers)
Closed 3 years ago.
I looked at other questions and I feel mine was different enough to ask.
I am sending a (potentially) large amount of information back to my backend, here is an example data set:
[ { orders: [Array],
_id: '5c919285bde87b1fc32b7553',
name: 'Test',
date: '2019-03-19',
customerName: 'Amego',
customerPhone: '9991112222',
customerStreet: 'Lost Ave',
customerCity: 'WestZone',
driver: 'CoolCat',
driverReq: false, // this is always false when it is ready to print
isPrinted: false, // < this is important
deliveryCost: '3',
total: '38.48',
taxTotal: '5.00',
finalTotal: '43.48',
__v: 0 },
{ orders: [Array],
_id: '5c919233bde87b1fc32b7552',
name: 'Test',
date: '2019-03-19',
customerName: 'Foo',
customerPhone: '9991112222',
customerStreet: 'Found Ave',
customerCity: 'EastZone',
driver: 'ChillDog',
driverReq: false,// this is always false when it is ready to print
isPrinted: false, // < this is important
deliveryCost: '3',
total: '9.99',
taxTotal: '1.30',
finalTotal: '11.29',
__v: 0 },
{ orders: [Array],
_id: '5c91903b6e0b7f1f4afc5c43',
name: 'Test',
date: '2019-03-19',
customerName: 'Boobert',
customerPhone: '9991112222',
customerStreet: 'Narnia',
customerCity: 'SouthSzone',
driver: 'SadSeal',
driverReq: false,// this is always false when it is ready to print
isPrinted: false, // < this is important
deliveryCost: '3',
total: '41.78',
taxTotal: '5.43',
finalTotal: '47.21',
__v: 0 } ] }
My front end can find all the orders that include isPrinted:false, I then allow the end user to 'print' all the orders that are prepared, in which, I need to change isPrinted into true, that way when I pull up a next batch I won't have reprints.
I was looking at db.test.updateMany({foo: "bar"}, {$set: {isPrinted: true}}), and I currently allow each order to set a new driver, which I update by:
Order.update({
_id: mongoose.Types.ObjectId(req.body.id)
},
{
$set: {
driver:req.body.driver, driverReq:false
}
which is pretty straight forward, as only 1 order comes back at a time.
I have considered my front end doing a foreach and posting each order individually, then updating the isPrinted individually but that seems quite inefficient. Is there a elegant solutions within mongo for this?
I'm not sure how I would user updateMany considering each _id is unique, unless I grab all the order's who are both driverReq:false and isPrinted:false (because that is the case where they are ready to print.
I found a solution, that was in fact using UpdateMany.
Order.updateMany({
isPrinted: false, driverReq:false
},
{
$set: {
isPrinted: true
}
consider there this special case where both are false when it needs to be changed too true. But I do wonder if there is a way to iterate over multiple document id's with ease.
I am pretty new to JavaScript and Mysql. MySQL query (which I have run in my server-side code in JS) returns rows in this form
i.e. console.log(rows) gives:-
[ RowDataPacket {
id: 7080,
post_author: 134,
post_title: '99 Varieties Dosa, Indira Nagar',
post_content: 'There',
link: '99-varieties-dosa-indira-nagar',
seo_keywords: null,
seo_desc: null,
seo_title: null,
best_for: 'Dosas',
special_info: '',
also_serves: 'Dosas',
'close-timing': '',
address: '56, 9th A Main Road',
direction_landmarks: 'Located in Indira Nagar',
seating: 'Unavailable',
longitude: '77.64097630979995',
latitude: '12.9777060556',
phone_no: ' ',
image_url: null,
location: 'Indira Nagar',
cuisine: 'South Indian Tiffin',
categories: 'Local Food',
Tags: 'Mysore Masala Dosa' }]
[ RowDataPacket {...}]
[ RowDataPacket {...}]
[ RowDataPacket {...}]
[ RowDataPacket {...}]
How can I access the location key of RowDataPacket Object?
I tried rows[i].location, rows[i]["location"], rows.location, rows[i].RowDataPacket.location etc.
When you are doing console.log(rows); you are getting data in the form of JSON array, which can be accessible using below code snippet:
$.each(rows, function(index, data){
// check your index & data details like below & perform other tasks
console.log('INDEX=', index);
consoel.log('DATA=', data); // Here data will be an object
// to access individual key data like location, you can try below code
console.log('LOCATION=', data.location);
});
For further reference you can go through link: https://api.jquery.com/each/
i building a monthly report for a customer via google analytics api, i built a factory function to handle the requests and everything, i get this json array from inside the factory function:
var months = {
paid_traffic: [
{plan: "", sales: ""},{plan: "", sales: ""},{plan: "", sales: ""},
{plan: "", sales: ""},{plan: "", sales: ""},{plan: "", sales: ""},
{plan: "", sales: ""},{plan: "", sales: ""},{plan: "", sales: ""},
{plan: "", sales: ""},{plan: "", sales: ""},{plan: "", sales: ""}
],
each object inside the array represent a month plan and sales.
i get details from google analytics and fill the object with it, till here everything works just fine, later on i need to calculate the total traffic for each month (i have few more object looks like that represent different google segments).
i have a problem with getting the results i garbed before in from google, it's keep return the empty initialized object my code look like this:
function calcTotalTraffic(){
for(var i in months.paid_traffic){
console.log(i,months.paid_traffic[i],months.paid_traffic);
}
}
my console.log looks like this from some wired reason:
0 Object {plan: "", sales: ""} [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
the last result (for the console.log(months.paid_traffic)) look like that when opened :
0: Object$$hashKey: "object:13"plan: ""sales: 99601__proto__: Object1: Object$$hashKey: "object:14"plan: ""sales: 93185__proto__: Object2: Object3: Object4: Object5: Object6: Object7: Object8: Object9: Object10: Object11: Object
as you can see from some reason it's return the original empty object.
any idea why it is happening??
p.s even if i manually months.paid_traffic[0] it'r return the same empty row..
thanks for the help, i appreciate it :)