This question already has answers here:
JavaScript variable number of arguments to function
(12 answers)
Closed 1 year ago.
In javascript I am in situation where i need to make variable arguments based on a length of an array, below is an sample code
function getValesList(json){
return getValues(json[0])+getValues(json[1])+getValues(json[2]);
}
function getValues(json1){
let valueList = Object.values(json1);
let valueListPipe = valueList.join("|");
return valueListPipe+lineSeparator;
}
where json is an array of JSON objects and I need to make a pipe delimiter file based on the length of incoming array. How to make it dynamic where I can do like a varargs in JAVA
If you're just passing N arguments of the same type, you can use the rest feature of Javascript for function arguments.
function getValuesList(...json){
return json.map(j => getValues(j)).join("");
}
This allows you go pass any number of separate arguments as in getValuesList(o1, o2, o3, o4) and the json parameter within your function will automatically be an array of however many arguments were passed.
Related
This question already has answers here:
access object through dot-syntax string path
(2 answers)
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 2 years ago.
I am having a problem which I think I might have figured out before how to do it but I can't remember now and can't figure it out.
Let's say we have an object thats a few levels deep, meaning it has as values other objects which also have as some of the values objects and so on.
Now how could I make a function to which I pass the object and and adress inside it and I can access the value at that location inside the function like this:
const getValueAtAdress = (object, 'country.city.rules') => {
return //here I need to return the value at object.country.city.rules.
}
Am I missing something obvious?
I thought I'd mention here for posterity that what helped me was the answer using the reduce which is exactly what I used before but I could not remember:
Example that I am using for my particular problem:
let stateLocation = address.split('.').reduce((acc, cur) => acc[cur], state);
Your code shows a function declaration but you can't declare an argument name in quotes
You can however call a function and pass a string.
In that case, you just need to split the string into an array and then loop over that array, building up a "chained" set of string indexes that can be passed to the object. The String.split() and Array.reduce() methods are the key.
let obj = {
county: {
city: {
rules: "Strict"
}
}
};
const getValueAtAddress = (object, countyCityRules) => {
// Split the string at the dots to form an array...
// The loop over that array and reduce it with an
// accumulator that is then applied to the object.
return countyCityRules.split(".").reduce((acc, cur) => acc[cur], obj);;
}
console.log(getValueAtAddress(obj, "county"));
console.log(getValueAtAddress(obj, "county.city"));
console.log(getValueAtAddress(obj, "county.city.rules"));
This question already has answers here:
JavaScript variable number of arguments to function
(12 answers)
Closed 2 years ago.
I have one doubt here that I need to pass n nos of values as argument and calculating the total sum of it using Javascript. I am explaining some sample code below.
function add(a,b,c) {
return a+b+c;
}
var data =add(5,6,7);
console.log(data)
Here I am passing only 3 arguments to the function but I need to pass n numbers of argument to the function like inside function its known how many values have passed as argument and final I need the total sum and return it.
You can either reduce over it to sum all if you want to write it in a functional way like
function add(...numbers) {
return numbers.reduce((acc,no) => return acc + no),0);
}
or by using arguments keyword knowing it's only available if the function is normal function, not an arrow function.
here's a ref https://stackoverflow.com/a/38567145/1888435
also, arguments aren't an array it's an array-like and if you checked typeof arguments it will give you object.
As #slappy said you can get parameters as array
function add(...numbers){
// Values reach as array
console.log(numbers)
// Here you should use array inner functions
return numbers.reduce((sum,value) => sum+value, 0)
}
let data = add(5,6,7);
console.log(data)
This question already has answers here:
How to explain callbacks in plain english? How are they different from calling one function from another function?
(34 answers)
Understanding Callbacks
(3 answers)
Closed 4 years ago.
How replacer argument function extract key and value from object value and mapped it to its key and value argument in JSON.Stringify(value, replacer, space) method.
I understood that key of the object become the key parameter of the replacer function and value become value parameter of this function.
let user={name:"anup", age:22};
JSON.stringify(user,function(key,value){
if(typeof value==="string"){
return undefined;
}
return value;
},null);
Here name becoming the key of the replacer function and "anup" becoming the value of the replacer function thats fine, but my question is how this mapping is happening?
Generally we call any method by passing argument in that method call, like
function a(c,d){
// logic
}
a(2,3);
But here in stringify method we are not passing any such thing to the replacer function or callback function, then how it is getting mapped?
Actually, I'm a newbie in javaScript world, so something I'm unable to understand. If you guide me in this regard , I'll be very thankful to you.
How JSON.stringify() works internally?
Thats probably some low level, highly optimized native code. But lets assume it is just a regular JavaScript function instead, that makes things easier. The function would be defined as such:
JSON.stringify = function(toStringify, replacer) {
Now that function has to determine what toStringify is first, e.g.:
if(typeof toStringify === "object") {
In that case, the code has to go over all the objects key/value pairs:
for(let key in toStringify) {
let value = toStringify[key];
Now the code can call the replacer with those pairs:
value = replacer(key, value);
Then a string can be built up as:
result += `"${key}": ${JSON.stringify(value)}`;
Then that result gets returned.
This question already has answers here:
How does the Math.max.apply() work?
(5 answers)
Closed 7 years ago.
Say for example I want the largest number out of an array of numbers.
var numbers = [54,34,76,33,87,12,76,92,44,93,23];
I want to be able to use Math.max() to find the largest number without using eval.
So, I want to be able to pass an array of parameters to a function. The array's length can change, so Math.max(numbers[0],numbers[1]...) won't work.
Is there any way I can do this?
You can use the .apply() method:
var max = Math.max.apply(Math, numbers);
The .apply() method is a property of Function.prototype and so is available on all function instances. Its first argument is used as the value of this in the function to be called, and the second argument should be an array that will be used as the list of parameter values.
In my example above I used Math as the value for this, because that's what this will be in a typical invocation of Math.max, but (on my installation of Firefox at least) Math.max.apply(null, numbers); works too.
This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 5 years ago.
This query returns a result db.graduates.find({student_id: '2010-01016'}).pretty()
and then I built a function
function findStud(name,value){ return db.graduates.find({name:value}); }
on the mongo shell when I run this findStud("student_id","2010-01016")
it does not display the results
You need to compose an query object with the key being the value in the nameparameter and value being the value in the parameter value.
function findStud(name,value){
var query = {};
query[name] = value;
return db.graduates.find(query);
}
By default when you don't do this, name is considered to be a String literal and the query gets executed as db.graduates.find({"name":value}); which searches for a key named name with the specified value, causing the query to fail.
See Also: Mongodb doesn't not update when I use like this