i was given a homework problem to be able to create a query string based on certain parameters in an array? I am still fairly new to javascript so have some success with it but would appreciate if someone can check my code please. Thank you to everyone in advance.
I am using forEach to loop through the array to get the values and using string concatenation to get some url. I have made a sample codepen for it.
https://codepen.io/anon/pen/pmRXzg
let Person = {
name: ['Sam', 'Daisy'],
food: ['banana', 'Apple']
}
let handler = Object.entries(Person)
handler.forEach(function(element) {
console.log(element)
})
let myUrl = Object.entries(handler).map(key => key + '=' +
handler[key]).join('&')
let visitUrl = "http://someURLString/?" + myUrl
console.log(myUrl)
console.log(visitUrl)
How can i get my final result to look like
someUrlString/?name=Sam,Daisy&food=banana,apple
You can use map() on Object.entries() and then join() entries by = and then join result by &
let Person = {
name: ['Sam','Daisy'],
food: ['banana','Apple']
}
let res = Object.entries(Person).map(x=> x.join('=')).join('&');
console.log(res)
Explanation:
Object.entiries() return an array of arrays. Each array contain key value pair. In this case entries will be [['name', ['Sam','Daisy']], ['food', ['banana','Apple']]].
Now we use map() on array. map() is takes a callback. It that callback first argument(in above case its x) is current element of array through which we are iterating. map() creates new array of same length based on the value returned from callback. In above case value returned is x.join('=')
join() is method which converts array to string by adding a given substring b/w each of them. So when apply join() on
[food , ['banana','Apple']].join('=')
it will become
"food=banana,Apple"
The array ['banana','Apple'] is converted to a string implicitly. So ['banana','Apple'] is banana,Apple
In the last part we get array ["name=Sam,Daisy","food=banana,Apple"] and we join() it by &.
The point is that when we array is converted to string. It returns string in which all elements are separated by ,
You can take advantage of .entries, .map and .join to:
Map [key,value] pairs of Person.
Transform their value to a single string, by eventually manipulating data.
Join them to return the final string.
let Person = {
name: ['Sam', 'Daisy'],
food: ['banana', 'Apple']
}
const res = Object.entries(Person).map(([entryName, entryValues]) => {
return `${entryName}=${entryValues.map(i => i.toLowerCase()).join(',')}`;
}).join('&');
const url = `someUrlString/?${res}`;
console.log(url);
Related
I have 2 arrays of objects with the same structure , each one of them came from database query. How can I map the cross section into a new array by comparing the ID value.
tempArray=[{city:london,subject:"testdata", id:7777}, {city:london,subject:"testdata", id:5555}]
tempArray1=[{city:london,subject:"testdata", id:8888}, {city:london,subject:"testdata", id:5555}]
I am trying to get the result:
newArray=[{city:london,subject:"testdata", id:5555}]
This is my try but I failed miserably:
let newArray=tempArray.map((x)=>{
if (x.id== tempArray1.forEach((doc)=>{
return doc.id})) {return x
}
})
You can use like below:
const filteredArray = tempArray.filter(obj1 => tempArray1.some(obj2 => obj1.id === obj2.id));
First:
If london is a string value, put it between Quotation marks.
Second:
Instead of using forEach you should use filter and some methods like below:
let newArray = tempArray.filter(x => tempArray1.some(doc => doc.id == x.id));
console.log(newArray)
The some method checks if any array elements pass a test (provided as a function).
The filter method creates a new array filled with elements that pass a test provided by a function.
You can check out the links: filter and some.
In javascript I need to join an array into a string with brackets. For example ['abc', 'yte', 'juu'] => (abc)(yte)(juu). I need the fastest and cleanest way to do this. I tried using the array join operator but it doesnt work on the first and last element.
You can do it with template literals. Use join() with )( separator, and wrap the result with ():
const data = ['abc', 'yte', 'juu'];
const result = `(${data.join(')(')})`;
console.log(result);
Thinking "I need the fastest and cleanest way to do this." is often not ideal. In most cases what people want is the most readable and understandable way to implement a solution.
I quite like the following. Where we first bracket each item in the array with map and then join the items with no delimiter:
const data = ['abc', 'yte', 'juu'];
let brackets = data.map(x => "(" + x + ")");
let result = brackets.join("")
console.log(result);
That of course takes two passes over the array. If you really must have the fastest solution just use a for loop:
const data = ['abc', 'yte', 'juu'];
let result = "";
for (let item of data) {
result += "(" + item + ")";
}
console.log(result);
In order to reduce an array to a single value (be that an object, array, string, number, ...) Javascript has the Array.prototype.reduce method, which achieves the desired result in a single loop and line:
console.log(['abc', 'yte', 'juu'].reduce((a,v)=>`${a}(${v})`,''))
const list = ['abc', 'yte', 'juu'];
const result = list.map(value => `(${value})`).join("");
console.log(result);
I have project in which I need to develop a specific calculator. By far everything is good but now I am stuck in one problem. I have an array of the object containing letter as key and its value as below
valueList = [{a:5}, {b:3}, {c:8}, {d:6}]
and I have an input element where user can type specific characters like this
input = "a+b-c"
how do I modifie the above string to the new string that contains values of alphabets from valueList like
newVar = "5+3-8"
I have tried below solution with no far success
const final = input.split("").map((variable) => {
return valueList.forEach((element) => {
if (variable === Object.keys(element)[0]) {
return Object.values(element)[0];
} else {
return variable;
}
});
});
console.log(final);
First turn the valueList into an object with multiple properties, rather than an array of objects with single properties. Then use a regular expression to match any of the keys of the objects, and use a replacer function to look up the matching value on the object:
const valueList = [{a:5}, {b:3}, {c:8}, {d:6}];
const obj = Object.assign({}, ...valueList);
const input = "a+b-c";
const pattern = new RegExp(
Object.keys(obj).join('|'),
'g'
);
const output = input.replace(pattern, match => obj[match]);
console.log(output);
If I have an array of strings that I would like to abbreviate with the filter() method.
How would I use filter() in combination with str.substring (or another string method if applicable)?
In the following code I would like to return the first four characters of each name, but it doesn't seem to be working.
JavaScript
let poshNames = ["Markol", "Andile", "Jazzmine", "Famisynth"];
let nickNames;
nickNames = poshNames.filter(function(name){
return name.str.substring(0,4);
});
You should use map:
const poshNames = ["Markol", "Andile", "Jazzmine", "Famisynth", "H"];
const nickNames = poshNames.map(name => name.substring(0,4));
console.log(nickNames);
Use map instead of filter
and it will work:
let poshNames = ["Markol", "Andile", "Jazzmine", "Famisynth"];
let nickNames;
nickNames = poshNames.map(function(name) {
return name.substring(0,4);
});
What filter does is essentially return an array that contains every element in the array for which the function returns true.
What map does, on the other hand, is return an array that contains the value the function returns for every value in the array.
Note: Both methods return a new array without affecting the original.
I am querying my db in node and have got the result in the form of an object like this - [ [1234] ].
I want to extract this value and convert it into a string and then pass it onto the client side. I have written the other required code but I am not able to get value from this object. Can anyone help me in getting the value and converting it to string?
Since, the result you've got is a two-dimensional array, you can get the value and convert it into a string (using toString() method) in the following way ...
var result = [ [1234] ];
var string;
result.forEach(function(e) {
string = e.toString();
});
console.log(string);
** this solution will also work if you have multiple results, ie. [ [1234], [5678] ]
You have a nested array, meaning that you have an array inside another array:
[ [1234] ]
// ^-^====^-^
To get the first value of the parent array, use the square brackets: [0]. Remember that indexes start at 0!
If you have val = [[1234]], val[0] gets the enclosed array: [1234]. Then, 1234 is a value in that array (the first value), so you use the square brackets again to get it: val[0][0].
To convert to string, you can use + "" which forces the number to become a string, or the toString() method.
var val = [[1234]];
var str = val[0][0] + "";
// or val[0][0].toString();
console.log(str, typeof str);
You can read more about arrays here.
var response = [ [1234] ];
console.log(response[0][0]);
to extract values from a string array or an array we can use .toString()
Ex:
let names = ["peter","joe","harry"];
let fname = names.toString();
output = peter ,joe,harry
or
let name:string[] = this.customerContacts.map(
res => res.firstname
let fname =name.toString();
Using De-structuring Array concept:
const arr = [[1, 2, 3, 4, 5]];
const [[p, q, r, s, t]] = arr;
console.log(p, q, r, s, t);
Output: 1 2 3 4 5