Adding quotation mark in array values - javascript

I have an array of strings in object form received from file, only I need to add quotation mark around parameter names of objects which are strings inside an array and around their values between square brackets to convert those strings to proper objects.
["{Durdham Hall Electric: [e4.kwh]}", "{University Hall Substation: [e1.kwh]}",
"{University Hall Substation: [e2.kwh]}"]
I have no idea how to loop through values and to add required symbol in required part.

Maybe change
options.push('<option value="' + '{' + data[devices][1] + ': ' + '[' + 'e' + i + '.kwh' + ']' + '}' + '" >' + meterName + '</option>')
to something like this, then you get a little nice parsable JSON
var data = [[0, 'Durdham Hall Electric:']],
devices = 0,
meterName = 'meterName',
i = 3,
options = [];
options.push('<option value="' + '{ \\"device\\": \\"' + data[devices][1] + '\\", \\"kwh\\": \\"' + 'e' + i + '\\"}' + '">' + meterName + '</option>');
alert(options);

You can use Regex and forEach to do this:
var data = ["{Durdham Hall Electric: [e4.kwh]}", "{University Hall Substation: [e1.kwh]}",
"{University Hall Substation: [e2.kwh]}"];
data.forEach(function(v,i){
data[i] = JSON.parse( v.replace(/{(.+):\s\[(.*)\]}/g, '{"$1":["$2"]}') );
});
console.log(data); // Open your console to see the results

If the strings are always starting with a { you can use substring and then combine the string back together.
String part1;
String part2;
String result;
String str = "{Durdham Hall Electric: [e4.kwh]}"
Then use index of to find the :
part1 = str.subString(1, str.indexOf(":"));
part2 = str.subString(str.indexOf(":"), str.length());
result = "{\"" + part1 + "\"" + part2;
Believe something like this could work however you do have to make some assumptions. This is only for a single element so you would have a loop for each item in your string array.

Related

How to freeze text from moving in console.log

So I have a simple console.log script that prints this
Now when I add a letter is moves
any way to freeze it please?
code
It would probably make more sense to make all of your cells contain a space character if they are "empty". Take a look here:
var Cell_1 = "a";
var Cell_2 = " ";
var Cell_3 = " ";
var Cell_4 = " ";
var Cell_5 = " ";
var Cell_6 = " ";
var Cell_7 = " ";
var Cell_8 = " ";
var Cell_9 = " ";
console.log(
Cell_1 + "|" + Cell_2 + "|" + Cell_3 + "\n" +
Cell_5 + "|" + Cell_6 + "|" + Cell_6 + "\n" +
Cell_7 + "|" + Cell_8 + "|" + Cell_9 + "\n" +
)
This way all of your variables are the same width - one character.
For future reference, here's some code that would probably look a bit nicer:
// This is called a 2d array: essentially an array containing other arrays.
// Its good for storing grids or tables of information.
var cells = [
['a', ' ', ' '],
[' ', ' ', ' '],
[' ', ' ', ' ']
]
// This uses Array.reduce() to generate the string.
// Google it once you feel more confident :)
console.log(
cells.reduce(
(totalString, currentRow) => totalString + currentRow.join('|') + '\n',
''
)
)
The question isn't very clear but I am assuming that you want to keep a grid aligned, the grid having multiple cells that can contain a character or not.
The problem is that the empty cells are initialised to "" (empty string) which is of size 0, but when a character is set the size will be 1, so it will shift all the following cells of 1.
An easy solution is to use a " " (space) for the empty cell instead of a "". As a result the size of a cell will always be 1 and the whole grid won't be shifted.

join() Not Removing Commas from Array

I am trying to complete a Kata whereby I create a phone number from a given array input.
Input: [1,2,3,4,5,6,7,8,9,0]
Output: (123) 456-7890
The issue I have is that once I have built my string, when I call join(''), the commas are not being removed. My results is still: (1,2,3) 4,5,6-7,8,9,0.
What is the issue with the code that is preventing this happening?
function createPhoneNumber(numbers){
var newNum = [];
newNum.push("(" + numbers.slice(0,3) + ")" + " " + numbers.slice(3,6) + "-" + numbers.slice(6,10));
return newNum.join('');
}
It sounds like the numbers parameter is an array:
function createPhoneNumber(numbers) {
var newNum = [];
newNum.push("(" + numbers.slice(0, 3) + ")" + " " + numbers.slice(3, 6) + "-" + numbers.slice(6, 10));
return newNum.join('');
}
console.log(createPhoneNumber('1234567890'.split('')));
In which case .sliceing it will produce another array, from the specified indicies, and using + with an array will result in concatenation. When the array gets implicitly turned into a string, its elements will be joined by a comma.
Join the sliced array while concatenating instead (and don't create a newNum array):
function createPhoneNumber(numbers) {
return "(" + numbers.slice(0, 3).join('') + ")" + " " + numbers.slice(3, 6).join('') + "-" + numbers.slice(6, 10).join('');
}
console.log(createPhoneNumber('1234567890'.split('')));
A nicer option would be to join the numbers into a string first:
function createPhoneNumber(numbers) {
const numStr = numbers.join('');
return `(${numStr.slice(0, 3)}) ${numStr.slice(3, 6)} - ${numStr.slice(6)}`;
}
console.log(createPhoneNumber('1234567890'.split('')));
I would recomment that you use template literals introduced in es6:
function createPhoneNumber(numbers){
const phNo = `(${numbers.slice(0,3)}) ${numbers.slice(3,6)}-${numbers.slice(6,10)}`
return phNo
}
createPhoneNumber('1234567890') // output ==> (123) 456-7890

Convert Javascript string to Dictionary

I'm trying to get Redis data in NodeJS. The Redis data needs to be converted to a dictionary for further processing. I gave it a try but finding difficult as parseFloat on string keeps giving me NaN.
Can anyone please help me to do it the correct way? Variable string has the sample data in below code. Please see the expected results below.
var string = "[ '[Timestamp(\'2018-06-29 15:29:00\'), \'260.20\', \'260.40\', \'260.15\', \'260.30\']' ]";
string = string.replace("[", "");
string = string.replace("]", "");
string = string.replace("[", "");
string = string.replace("]", "");
s1 = string
var array = string.split(",");
var final = "{" + "\"date\"" + ":" + "\"" + array[0] + ",\"Open\"" + ":" + "\"" + array[1].trim() + "\"" + ",\"High\"" + ":" + "\"" + array[2].trim() + "\"" + ",\"Low\"" + ":" + "\"" + array[3].trim() + "\"" + ",\"Close\"" + ":" + "\"" + array[4].trim() + "\"" + "}";
console.log(final);
Expected Result:
{
"date": " Timestamp('2018-06-29 15:29:00')",
"Open": "260.20",
"High": "260.40",
"Low": "260.15",
"Close": "260.30"
}
You have extra apostrophes at both sides of your string which is not needed and while parsing parseFloat("'260.20'")it returns NaN. You could remove them from the array as below:
array = array.map( (str) => str.replace(/'/g, '') );
parseFloat(array[1]); // 260.20
It would probably be a whole lot easier to split the string by single-quotes, then combine into an object:
const string = "[ '[Timestamp(\'2018-06-29 15:29:00\'), \'260.20\', \'260.40\', \'260.15\', \'260.30\']' ]";
const [,,timestamp,,Open,,High,,Low,,Close] = string.split("'");
const obj = {
date: `Timestamp('${timestamp}')`,
Open,
High,
Low,
Close
}
console.log(obj);
Note that \' inside a string delimited by double-quotes doesn't do anything - it's the same as '. (If you need a literal backslash, use \\)

Passing a variable through to an array mid string

I have an array like this:
var array = [
'Hey there, ' + name + '!',
'It\'s nice to see ' + name + ' join us.',
'Everybody welcome ' + name + '!',
'Thanks,' + name
]
I get an error stating that name is undefined, so if I put name = ''; before it, and loop through the array, it just says
Hey there, !
It's nice to see join us.
Everybody welcome !
Thanks,
Is there a way I can do something like:
name = 'Albz'
console.log(array[0]);
and have it echo out
Hey there, Albz!
The name variable is dynamic and changes on each iteration of forEach, so it can't be hardcoded, and I'd like to not have to redeclare the array every single time as it's quite lengthy.
Is there a way to do this?
var nameArr = ['Ayan', 'Arnab', 'Akash'];
function process(name) {
return [
'Hey there, ' + name + '!',
'It\'s nice to see ' + name + ' join us.',
'Everybody welcome ' + name + '!',
'Thanks,' + name
];
}
for (var i = 0, len = nameArr.length; i < len; i += 1) {
console.log(process(nameArr[i])[0]);
}

Javascript regex replace yields unexpected result

I have this strange issue, hope that someone will explain what is going on.
My intention is to capture the textual part (a-z, hyphen, underscore) and append the numeric values of id and v to it, underscore separated.
My code:
var str_1 = 'foo1_2';
var str_2 = 'foo-bar1_2';
var str_3 = 'foo_baz1_2';
var id = 3;
var v = 2;
str_1 = str_1.replace(/([a-z_-]+)\d+/,'$1' + id + '_' + v);
str_2 = str_2.replace(/([a-z_-]+)\d+/,'$1' + id + '_' + v);
str_3 = str_3.replace(/([a-z_-]+)\d+/,'$1' + id + '_' + v);
$('#test').html(str_1 + '<br>' + str_2 + '<br>' + str_3 + '<br>');
Expected result:
foo3_2
foo-bar3_2
foo_baz3_2
Actual Result:
foo3_2_2
foo-bar3_2_2
foo_baz3_2_2
Any ideas?
JS Fiddle example
Your pattern:
/([a-z_-]+)\d+/
matches only "foo1" in "foo1_2", and "foo" will be the value of the captured group. The .replace() function replaces the portion of the source string that was actually matched, leaving the remainder alone. Thus "foo1" is replaced by "foo3_2", but the original trailing "_2" is still there as well.
If you want to alter the entire string, then your regular expression will have to account for everything in the source strings.
Just try with:
str_1 = str_1.match(/([a-z_-]+)\d+/)[1] + id + '_' + v;
Use this instead to capture 1_2 completely:
str_1 = str_1.replace(/([a-z_-]+)\d+_\d+/,'$1' + id + '_' + v);
Because you want to replace _2 also of string. Solution can be this:
str_1 = str_1.replace(/([a-z_-]+)\d+_\d/,'$1' + id + '_' + v);
str_2 = str_2.replace(/([a-z_-]+)\d+_\d/,'$1' + id + '_' + v);
str_3 = str_3.replace(/([a-z_-]+)\d+_\d/,'$1' + id + '_' + v);
DEMO
Your pattern actually includes the first digits, but it will store only the textual part into $1:
foo1_2
([a-z_-]+)\d+ = foo1
$1 = foo
The pattern stops searching at the first digits of the string.
if you want to replace any characters after the textual part, you could use this pattern:
/([a-z_-]+)\d+.*/

Categories

Resources