group redundant object value into array object - javascript

["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);

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

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

How I can print string in javascript

I want to print a string in following manner 'abc',21,'email' in javascript how can I do. below is my code.
var data = [];
data.push('abc');
data.push(21);
data.push('email');
Write a function to quote a string:
function quote(s) {
return typeof s === 'string' ? "'"+s+"'" : s;
}
Now map your array and paste the elements together with a comma:
data . map(quote) . join(',')
Since joining with a comma is the default way to convert an array into a string, you might be able to get away without the join in some situations:
alert (data . map(quote));
since alert converts its parameter into a string. Same with
element.textContent = data . map(quote);
if data is an array defined as
var data = [];
data.push('abc');
data.push(21);
data.push('email');
the use join() method of array to join (concatenate) the values by specifying the separator
try
alert( "'" + data.join("','") + "'" );
or
console.log( "'" + data.join("','") + "'" );
or simply
var value = "'" + data.join("','") + "'" ;
document.body.innerHTML += value;
Now data = ['abc', 21, 'email'];
So we can use forEach function
var myString = '';
data.forEach(function(value, index){
myString += typeof value === 'string' ? "'" + value + "'" : value;
if(index < data.length - 1) myString += ', ';
});
console.log(myString)
Shorter version:
myString = data.map(function(value){
return typeof value === 'string' ? "'" + value + "'" : value;
}).join(', ');
console.log(myString);
JSFiddle: https://jsfiddle.net/LeoAref/ea5fa3de/

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