Convert Javascript string to Dictionary - javascript

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 \\)

Related

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

group redundant object value into array object

["name: edward, subjectId:1, remark:passed",
"name: edward, subjectId:3, remark:passed",
"name: Jamie, subject:1, remark:excellent"]
Above is a messed up output which I have no power to control. I have to map it and clean that up. The ideal array object have to be like below :
[{name:"edward",subjectId:1,3,remark:"passed},{name:"Jamie",subjectId:1,remark:"excellent"}]
But for me it seems impossible because it doesn't have unique id for each record. I can compare the remark and group the subjectId properly, but what if it has a row that inserted on not the same date? Then my logic flawed. Any thought?
Try using Array.prototype.map() ; String.prototype.replace() with RegExp /(\w+)(?=:|,|$)/g to match words followed by ":", "," or end of string , replace with quoted string ; JSON.parse()
var arr = ["name: edward, subjectId:1, remark:passed",
"name: edward, subjectId:3, remark:passed",
"name: Jamie, subject:1, remark:excellent"
];
var res = arr.map(function(val) {
return JSON.parse("{" + val.replace(/(\w+)(?=:|,|$)/g, "\"$1\"") + "}")
});
console.log(res);
document.querySelector("pre").textContent = JSON.stringify(res, null, 2)
<pre></pre>
Your input is so close to being JSON, it's a shame you have to throw string manipulation at it!
var input = [
"name: edward, subjectId:1, remark:passed",
"name: edward, subjectId:3, remark:passed",
"name: Jamie, subject:1, remark:excellent"
];
function makeJson(str) { // Deal with each of your input strings
function wrapKeyAndVal(str) { // Wrap the key and value pairs in double quotes
var key = str.split(':')[0].trim();
var val = str.split(':')[1].trim();
return '"' + key + '"' + ':' + '"' + val + '"';
}
return str.split(',').map(wrapKeyAndVal).join(',');
}
input = input.map(makeJson);
// Parse each string into an object
var output = input.map(item => JSON.parse("{" + item + "}"))
// You'll end up with an array of objects
console.log(output);

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+.*/

Adding quotation mark in array values

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.

Javascript : expected error

I am unable to decipher the error message Expected :. It occurs when it attempts to execute the code below. I have a string of characters e.g. "Joe":"HR" being passed to it
var p = {
"\"" + m[0] + "\"" + " : " + "\"" + (m[0] = m[1]) + "\""
};
Additional code
for (var key in p)
{
if (p.hasOwnProperty(key))
{
client = selectedPackage.Elements.AddNew(key, p[key]);
client.Update();
}
}
You're defining an object, but only have a key without value, e.g. you're trying to do:
var p = {
key : value
}
But your code is only
var p = {
key
}
You have a :, but since it's inside a string (" : "), it doesn't count.
{} is an object, so it expects a value for the key:
{
"key": "value"
}
In your case, the key is "\"" + m[0] + "\"" + " : " + "\"" + (m[0] = m[1]) + "\"" (which is actually invalid, the error is a little unclear on this), so you need to specify a value as well.
I suspect you want this (from your string, which looks like JSON):
var p = { };
p[m[0]] = m[1];
You don't create an object with a variable key and value by concatenating the text of a literal. You have to use array-style assignment:
var p = {};
p[m[0]] = m[1];

Categories

Resources