I have the following code I'm working on:
function price ([arg1,arg2]) {
let city1 = {coffee:0.5, water:0.8, beer:1.2, sweets:1.45, peanuts:1.6};
let city2 = {coffee:0.4, water:0.9, beer:1.4, sweets:1.25, peanuts:1.8};
console.log (arg1[arg2]);
}
price (["city1","water"])
What I'm trying to achieve here is, have the price of a particular product be listed when you call the function with the city name and the product.
From what I can see, it's because "city1" gets input as a string, which is why I get no results when calling the function. Any ideas how I can convert the arg1 input from string to an object?
I looked into using window and eval, but I wasn't able to find a way to properly use them in this one. I know it's a dumb question, and that I'm probably missing something obvious, but I pretty much tried everything I can think of.
Just rethink how you're using the objects. By using the bracket notation rather than the dot notation for accessing object properties you are able to pass in a string, which is helpful for getting values not known beforehand. Below is an example but do note you also should check if the property actually exists as well.
Also worth mentioning is that you shouldn't pass your argument in as an array like that. Either pass them in directly or use an object.
function price (city, item) {
let cities = {
city1 : {coffee:0.5, water:0.8, beer:1.2, sweets:1.45, peanuts:1.6},
city2 : {coffee:0.4, water:0.9, beer:1.4, sweets:1.25, peanuts:1.8}
}
let res = cities[city][item]
console.log(res)
return res;
}
price ("city1", "water")
You could use the cities as key for an object and access it via a key, as well as the key for the product.
function price(city, product) {
return (data[city] || {})[product];
}
var data = { city1: { coffee: 0.5, water: 0.8, beer: 1.2, sweets: 1.45, peanuts: 1.6 }, city2: { coffee: 0.4, water: 0.9, beer: 1.4, sweets: 1.25, peanuts: 1.8 } };
console.log(price("city1", "water"));
console.log(price("foo", "bar"));
Related
If I use the params for pass a list in GET method:
fetch_physicalserver_list(){
var params = {
id_list: this.physicalserver_id_list // there is [24, 26, 27]
}
this.$Lml_http('get', this.$Api_urls.user_productmanage_physicalserver.list(), params, response => {
this.physicalserver_list = response.data.results
console.log( response.data.results)
}, error => {
})
}
And in the request, the id_list convert to the id_list[]=24&id_list[]=27&id_list[]=27.
and I don't know how to get the id_list in the backend.
I use the method to get the id_list[] I will only get the first id, if I get id_list, I will get nothing.
the code of get_param_from_query_params method:
def get_param_from_query_params(query_params, param):
param_temp = None
try:
mutable = query_params._mutable
query_params._mutable = True
param_list = query_params.pop(param)
param_temp = param_list[0] if (isinstance(param_list, list) and len(param_list) > 0) else ''
query_params._mutable = mutable
except Exception as e:
pass
return param_temp
So, I have two questions:
1.The params's id_list converted to id_list[]. where is the official description?
2.How can I get the id_list after I passed to the backend?
Firstly, you are using the key id_list[], so you must use id_list[] to retrieve the key in Django. Including [] in JavaScript is a convention to show there are multiple values, but it makes no difference to Django.
If you want a list of values instead of a single value, then use pop_item instead of pop.
It's not clear to me why you need the get_param_from_query_params method. You are returning param_list[0] which means you'll only ever get a single item. It would be much simpler to use getlist:
id_list = query_params.getlist('id_list')
I got the following obj that I use to store setting parameters. It holds default values I wanna make the properties of this obj be overwritten by a JSON that comes in via POST request. Sure, I can convert every string value from the JSON indivually and assign it to the corresponing property, however, whats a good practise for that?
const moth_eng = require('./fractioning_model_v1.1.js');
// in ./fractioning_model_v1.1.js set default values
var settings = {
i: 1,
rev_share: 0.2,
parent_level_share: 0.45,
d: 2,
get user_pool_share () {return this.i - this.rev_share;},
get remaining_levels_pool () {return this.user_pool_share - this.parent_level_share;},
};
//main.js
app.post('/fractobj', function (req, res) {
logger.log("info", "/fractobj requested - post")
let obj = req.body;
moth_eng.set_sttngs(obj);
res.send(moth_eng.getFractions(10));
});
// in ./fractioning_model_v1.1.js
function setSettings(obj){
Object.assign(settings, obj);
}
My Problem is, that the Object.assign() does assign the values as strings, since the values of the JSON are string and I find it uncool to individually convert those values for each value.
Whats a proper way to solve this problem in the big picture?
I'm creating a very simplified version of a drag and drop shopping cart with jqueryui.
My issue is regarding adding data(id, name, price) to an array.
I tried several methodes of adding the data (also an array) to the main container(array). But I keep getting this error: Uncaught TypeError: undefined is not a function
var data = [];
function addproduct(id,name,price){
//var d = [id,name,price];
data[id]["name"] = name;
data[id]["price"] = price;
data[id]["count"] = data[id]["count"]+1;
console.log(data);
}
the addproduct() function can be called by pressing a button
It is not entirely clear to me what type of data structure you want to end up with after you've added a number of items to the cart. So, this answer is a guess based on what it looks like you're trying to do in your question, but if you show a Javascript literal for what you want the actual structure to look like after there are several items in the cart, we can be sure we make the best recommendation.
You have to initialize a javascript object or array before you can use it. The usual way to do that is to check if it exists and if it does not, then initialize it before assigning to it. And, since you're keeping a count, you also will want to initialize the count.
var data = [];
function addproduct(id,name,price){
if (!data[id]) {
// initialize object and count
data[id] = {count: 0};
}
data[id]["name"] = name;
data[id]["price"] = price;
++data[id]["count"];
console.log(data);
}
And FYI, arrays are used for numeric indexes. If you're using property names like "name" and "price" to access properties, you should use an object instead of an array.
And, I would suggest that you use the dot syntax for known property strings:
var data = [];
function addproduct(id,name,price){
if (!data[id]) {
// initialize object and count
data[id] = {count: 0};
}
data[id].name = name;
data[id].price = price;
++data[id].count;
console.log(data);
}
It looks like what you want is an array of objects, although I would need a more detailed description of your problem to be clear.
var data = []
function addproduct(id, name, price)
{
data.push({'id': id, 'name':name, 'price': price, 'count': ++count});
console.log(data);
}
I'll cut straight to the chase. I'm getting a json object with another object inside of it like so:
function getName(summonerName, region) {
LolApi.Summoner.getByName(summonerName, region, function(err, summoner) {
if(!err) {
console.log(summoner);
}
});
}
However, the result of this call is (let's stay summonerName is "tetsii"):
{ tetsii:
{ id: 51520537,
name: 'tetsii',
profileIconId: 23,
summonerLevel: 23,
revisionDate: 1408307600000
}
}
Now, I can access the id's and stuff with "console.log(summoner.tetsii.id)" for example, but because the summonerName (in this case "tetsii") can be anything, I prefer not to do it like so. So, my question is: how to access the first object inside a JSON or is there another way? And no, I can't get an array in this case afaik.
I would like to note that I've tried "console.log(summoner.summonerName.id)", but that doesn't yield results as summonerName is a string.
Thanks everybody
EDIT: Got the answer. By simply using summoner[summonerName].id I am able to grab the id. Thanks everyone for answers!
-Tetsii
By using Object.keys. For example, if you know that summoner will only have a single top-level key, you can get it with:
var summonerName = Object.keys(summoner)[0];
Obligatory browser support notice: IE < 9 does not support this out of the box, but you can use a polyfill provided in the MDN page as a compatibility shim.
There is no order in objects, so there's no guarantee you'll get the object you think, but using Object.keys and shift() you can do
var first = summoner[Object.keys(summoner).shift()];
If there is no way to return it as an array, the best idea is to iterate over the object properties as documented in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
The most important part is:
for (var prop in summoner) {
console.log("summoner." + prop + " = " + summoner[prop]);
}
Tested in console:
var summoner = { tetsii:
{ id: 51520537,
name: 'tetsii',
profileIconId: 23,
summonerLevel: 23,
revisionDate: 1408307600000
}
};
yields:
summoner.tetsii = [object Object]
I'm new to Javascript, and I'm learning how to use OOP principals. I'm stuck on assigning object properties and then accessing them later.
Let's say I have this function that assigns properties to an object "Car".
function assignProps()
{
Car.size="small";
Car.cost="expensive";
}
The object Car with empty properties because they are assigned from the function.
var Car =
{
size:"",
cost:"",
returnSize: function()
{
return this.size;
},
returnCost: function()
{
return this.cost;
},
}
Now, I want to call the function that assigned the value, and then access Car's properties. I tried doing this, but it obviously failed:
function accessProps()
{
assignProps();
console.log(Car.returnSize());
console.log(Car.returnCost());
}
Any help would be appreciated. I have a feeling that this might have to do with constructors or prototypes, but since there are so many ways to create custom objects in Javascript, the documentations are very confusing.
EDIT: By "fail" I mean that it outputs the blank instead of the newly assigned value
EDIT: I tried doing it this way as well, and it yielded the same result.
You have some errors in your code:
var Car = {
size:"",
cost:""
}
And if you look at this fiddle: http://jsfiddle.net/JskBy/
It works as expected.
Full code:
function assignProps() {
Car.size="small";
Car.cost="expensive";
}
var Car ={
size:"",
cost:""
}
function accessProps(){
assignProps();
console.log(Car.size);
}
assignProps();
accessProps();
You have a syntax error on your car object initialization, should be
var Car = { size: "", cost: "" };
Line 18, column 14: Extra comma.
Line 20, column 2: Missing semicolon.
Try to get a developing tool with JSLint/JSHint built-in (e.g. Notepad++ with add-on), it might help you with debugging problems like this.