get numbers from string and use them to create an object javascript - javascript

So I would have the next string:
const string = "1,22, 28,40,4, 8,24,31,33"
var config = {
config_key: config_key,
location_key: null,
autoassign: 1,
}
I would need to create 9 objects from this string where the location_key: is equal with a value in the string, the other object prop. remains the same.

Split the string on /, ?/ (comma and optional space) then map those values to new objects, using config as a template and override the location_key using the string value.
const string = "1,22, 28,40,4, 8,24,31,33"
const config = {
config_key: 'config_key',
location_key: null,
autoassign: 1,
}
const parsed = string.split(/, ?/).map(location_key => ({
...config,
location_key
}))
console.info(parsed)
Since your question states...
where the location_key: is equal with a value in the string
I assumed you wanted to keep the values from the string as strings but if you want them treated as actual numbers (integers), use
location_key: parseInt(location_key, 10)

I would use a constructor to create each new instance of an Object:
const string = "1,22, 28,40,4, 8,24,31,33", config_key = 'testing';
function Config(locationKey){
this.config_key = config_key;
this.location_key = +locationKey;
this.autoassign = 1;
}
const nums = string.split(/\s*,\s*/), objs = [];
nums.forEach(n=>{
objs.push(new Config(n));
});
console.log(objs);

Related

returning an array from an array prototype if there is any

Here is a working example of what I want to do:
let value = " Have you ever * looked* sam [5, 6]";
// let value = " Have you ever * looked* sam"; // we may have this instead
// So far I need to check if there is []
if(value.includes('[')){
const archiveGuidePure = value.substring(value.indexOf('['), value.length);
value = value.replace(archiveGuidePure, "");
const archiveGuide = JSON.parse(archiveGuidePure);
console.log(archiveGuide);
}
console.log(value);
As you see we have a string in value and the string might have an array prototype at the very end of it. note that sometimes we want that array and sometimes we don't.
The code checks the value to see if there is an array.
if there is an array it removes the array and returns it as an array. if there is not an array at the end of value then nothing changes.
So far I need to check if there is a [ sign otherwise I get an error which made my code ugly and in my mind a bad practice.
How do you do this without if statement?
Use regex and replace and no need to check
let value = " Have you ever * looked* sam [5, 6]";
const newValue = value.replace(/\[.+\]/, '');
// if there is no array in the string then it will be null or you can give it a default value
const array = JSON.parse(value.match(/\[.+\]/)) || [];
console.log(newValue);
console.log(array);
Update:
if you implement JSON.parse() more correctly you need to send string parameter
let value = " Have you ever * looked* sam [5, 6]";
const newValue = value.replace(/\[.+\]/, '');
const stringify = value.match(/\[.+\]/);
// if there is no array in the string then it will be null and you can give it a default value
const array = stringify
? JSON.parse(stringify[0])
: [];
console.log(newValue);
console.log(array);
let value = " Have you ever * looked* sam [5, 6]";
const query = /(\[.+\])/gi
const found = value.match(query);
if (found) {
const result = JSON.parse(found[0])
console.log(result)
}
You do no need to check if a '[' exists. The method replace will find it.
const p = 'Have you ever * looked* sam [5, 6]';
var newValue = p.replace( p.substring(p.indexOf('['), p.indexOf(']')+1), '');
var array = JSON.parse( p.substring(p.indexOf('['), p.indexOf(']')+1));
console.log(newValue)
console.log(array)
You replace the array, from when it is opened (p.indexOf('[')), until it is closed (p.indexOf(']')+1)

How to convert comma separated strings enclosed within bracket to array in Javascript?

How to convert below string to array in Javascript? The reason is that I want to take both value separately.
The string is value from an element, when I print it to console I got:('UYHN7687YTF09IIK762220G6','Second')
var data = elm.value;
console.log(data);
You can achieve this with regex, like this for example :
const string = "('UYHN7687YTF09IIK762220G6','Second')";
const regex = /'(.*?)'/ig
// Long way
const array = [];
let match;
while (match = regex.exec(string)){
array.push(match[1]);
};
console.log(array)
// Fast way
console.log([...string.matchAll(regex)].map(i => i[1]))
source
let given_string = "('UYHN7687YTF09IIK762220G6','Second')";
// first remove the both ()
given_string = given_string.substring(1); // remove (
given_string = given_string.substring(0, given_string.length - 1); // remove )
let expected_array = given_string.split(',');
console.log(expected_array);

how can I find the lowest value in my array in JS?

I have the following code that calculates the highest value in my set of values:
var collection = [];
$histogram.find('li').each(function() {
collection.push($(this).data());
});
component.props.collection = collection;
// Find Histogram max value
collection.hasMax = function(value) {
return this.reduce(function(prev, curr) {
return prev[value] > curr[value] ? prev : curr;
});
};
// Assign Max Value
component.props.maxRange = collection.hasMax('value').value;
I need to create a second function that does the same, but for the lowest values, e.g. the function called hasMin. I thought it would be enough to just change the comparision here:
return prev[value] < curr[value] ? prev : curr;
but I tested it and it didn't work, can you help me with that?
JavaScript's built-in Math object has a static Math.min() method, which seems to solve your problem without the need for all that code you are using.
You can get the lowest value of an array by using JavaScript's destructuring assignment (to turn the array into a comma separated list of values) and pass that list to the method.
There's also Math.max().
let myData = [1,2,3,4,5,6,7,8,9,10];
console.log(Math.min(...myData));
console.log(Math.max(...myData));
You've indicated that collection is an array of objects and each object has a value property and you need to get the lowest and highest values in that object array so this will do it:
// This is just set up to emulate your data structure. Don't add this:
var sth = "test", sth2 = "test", sth3 = "test";
let component = { props: {} };
let collection = [{value:0, label: sth},{value:1, label: sth2},{value:3, label:sth3}];
// Assuming your data structure is set up, the following will get you there:
// Loop over the array of objects, extracting the value property of each object into a new array
let vals = collection.map(function(obj){
return obj.value; // Place the value of each object into an array
});
// Just set your object's properties to the min and max of the destructured array
component.props.minRange = Math.min(...vals);
component.props.maxRange = Math.max(...vals);
console.log(component.props.minRange, component.props.maxRange);
with ES5:
let sth = "test", sth2 = "test", sth3 = "test";
let component = { props: {} };
let collection = [{value:0, label: sth},{value:1, label: sth2},{value:3,
label:sth3}];
// Assuming your data structure is set up, the following will get you there:
// Loop over the array of objects, extracting the value property of each
object into a new array
let vals = collection.map(function(obj){
return obj.value; // Place the value of each object into an array
});
// Just set your object's properties to the min and max of the destructured array
component.props.minRange = Math.min.apply(Math,vals);
component.props.maxRange = Math.max.apply(Math,vals);
console.log(component.props.minRange, component.props.maxRange);

Creating a two-dimensional object from a string of values

In JavaScript, how would I create a two-dimensional object from a string of values, in which the first value would be the name, the last is the content, and all other values in between are properties?
For example, I have a string "capitals,Asia,China,Beijing" and I want the code to split this string into four values and create an object capitals["Asia","China"] = "Beijing";.
How could I do that?
In a complete code piece that would look like this:
<script>
Values = "capitals,Asia,China,Beijing";
Values = Values.split(",");
alert(capitals["Asia","China"]);
</script>
I want the alert box to show me the word Beijing.
How could I do that?
JavaScript does not have two-dimensional arrays or objects that you can access using array[index1, index2] as in some other languages. To do this, you have to use nested objects/arrays, such as
capitals["Asian"]["China"]
To create these, you can do something like:
function makeEntry(obj, str) {
const parts = str.split(','); // array of comma-delimited values
const value = parts.pop(); // final value ("Beijing")
const final = parts.pop(); // final property ("China")
// Find nested property, creating empty object if not there.
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (!(parts in obj)) obj[part] = {};
obj = obj[part];
}
// Set final value.
obj[final] = value;
}
const data = {};
makeEntry(data, "capitals,Asian,China,Beijing");
console.log(data);
console.log(data.capitals["Asian"]["China"]);
This code will work even if there are more levels, such as "capitals,Asia,East Asia,China,Beijing".
Note that there is no way to create a variable in JS given a name. Therefore, we provide an initial object, and build the nest structure within it.
Another approach
Another approach is to create a single-level object with keys such as "capitals,Asian,China". That's easier to create, but might be more inconvenient to access. For example, there would be no easy way to find all the Asian capitals. Below, I'm using regexp to pick apart the input into the first part and the final value.
function makeEntry(obj, str) {
const [, key, value] = str.match(/(.*),([^,]+)$/);
obj[key] = value;
}
const data = {};
makeEntry(data, "capitals,Asian,China,Beijing");
console.log(data);
console.log(data["capitals,Asian,China"]);
You can use WeakMap to set the key of the WeakMap object to an object; Array.prototype.shift(), Array.prototype.splice(), Array.prototype.pop() to set the value of the WeakMap object instance.
let Values = "capitals,Asian,China,Beijing";
Values = Values.split(",");
const capitals = {[Values.shift()]:Values.splice(0, 2)};
const wm = new WeakMap;
wm.set(capitals, Values.pop());
console.log(wm.get(capitals));
You can alternatively set the property of an object to the result of JSON.stringify() called on Values.splice(1, 2)
let Values = "capitals,Asian,China,Beijing";
Values = Values.split(",");
const key = JSON.stringify(Values.splice(1, 2));
console.log(key);
const map = {[Values.shift()]:{[key]:Values.pop()}};
console.log(map.capitals[key]);

Why an object key's first value is treated as a string - AngularJs

I have an object named as "param" and it has a key named as "item[]". The values of item[] are inserted dynamically.
Problem is when "item[]" has a single value, it treats that value as a string and not as first index of array.
Example :
item[]="123";
but when it has multiple values then it treats itself as an array which is desired, example-
item[] = ["123","456"];
I want the single value also as index of this array like
item[] = ["123"]
How would I do it ?
P.S. - This object is created from querystring parameters like http://example.com/def?item[]=123&item[]=456, then when I extract querystring, it returns these parameters as the keys of an object
I am extracting querystring in this way(Javascript)-
var param = $location.search();
console.log('Param');
console.log(param);//Returns Object{item[]=[2]} in console
This is because variableName[] is not a javascript syntax.
Since it does not recognise the [], it is probably part of the name if it does not throw an error.
To create an array, you have 2 possibilities :
//Contsructor
var ar = new Array(); //empty array
//Literal
var ar = []; //same as above
var ar = [0,1,2,3]; //array of length 4
var ar = new Array(4); //empty array of length 4
to access or set it
var ar[0] = "value"
Try this
queryString = ["123"];
queryString = ["123","432","456"];
if(queryString.length==1){
item.push(queryString[0]);
}else{
angular.forEach(queryString,function(value,key){
item.push(value);//push only value
})
}
I have solved it -
if(typeof param['item[]'] == "string"){
param['item[]'] = [param['item[]']];
}
First I am checking if the key has a string value, if it is string then I am converting it into an array and it worked.
Here is the working fiddle -
https://jsfiddle.net/r3vrxzup/

Categories

Resources