How to convert string array to JSON array in Javascript? - javascript

I have string array like this:
"[totRev=248634.29858677526, totEBITDA=34904.9893085068, EBITDA_Operating_Cash_Flow_Margin=0.140386863387, debt_Service_Coverage_Ratio=16.7793849967, gross_Debt_to_EBITDA=0.3626422278, gross_Debt=50632.09233331651, cash_Available_for_Debt=102746.09168349924, debt_Servicing_Amount=6123.352655871018]"
How do I convert this either into a JSON Array or a JSON object like
{totRev:'248634.29858677526',....etc}

Use substring, split and reduce
str.substring( 1,str.length - 1 ) //remove [ and ] from the string
.split(",") //split by ,
.reduce( (a,b) => (i = b.split("="), a[i[0]] = i[1], a ) , {} );
Reduce explanation
Split b (element in the array such as totRev=248634.29858677526) by =
Assign the first item in the array as key to a (accumulator initialized as {}) and value as second item of the array
Return a
Demo
var str = "[totRev=248634.29858677526, totEBITDA=34904.9893085068, EBITDA_Operating_Cash_Flow_Margin=0.140386863387, debt_Service_Coverage_Ratio=16.7793849967, gross_Debt_to_EBITDA=0.3626422278, gross_Debt=50632.09233331651, cash_Available_for_Debt=102746.09168349924, debt_Servicing_Amount=6123.352655871018]";
var output = str.substring(1,str.length-1).split(",").reduce( (a,b) => (i = b.split("="), a[i[0].trim()] = i[1], a ) , {} );
console.log(output);

Related

How to remove a duplicate array from inside a nested array?

I would like to remove duplicated arrays from a 2D array.
For example I have this 2D array:
[[-1,0,1],[-1,-1,2],[-1,0,1]]
and I want to remove the duplicate to only have this:
[[-1,0,1],[-1,-1,2]]
I tried:
arr.filter((v, i, a) => a.indexOf(v) == i)
but this only works for primitive data types, not objects like arrays.
You can use Set method. The Set object stores unique values of any type, and automatically removes duplicates.
First convert all the sub arrays into string which can be compared. Then add them to Set to remove duplicates. Then convert the Set of strings to array by using Array.from(). At last parse the JSON object.
let arr = [[-1,0,1],[-1,-1,2],[-1,0,1]];
let uniqueArr = Array.from(new Set(arr.map(JSON.stringify))).map(JSON.parse);
console.log(uniqueArr); // output: [[-1,0,1],[-1,-1,2]]
This should remove duplicates and retain the original order; that is, it will remove the duplicates in place. Of course, I didn't test every possible case and there may be a more clever way to accomplish the same.
let aOrig = [[-1,0,1],[-1,0,1],[-1,-1,2],[-1,-1,2],[-1,0,1],[2],[-1,0,1,1],[-1,0],[2]],
a = new Array(),
c = new Array()
order = new Array();
aOrig.forEach( (v,i) => a.push([v.toString(),i]) );
a.sort((a,b) => a[0] < b[0] );
//a.forEach ( v => console.log(v[0].toString() + " : " + v[1]));
order.push(a[0][1]);
for (i=1, l=a.length; i < l; i++) {
if ( a[i][0] != a[i-1][0] ) {
order.push(a[i][1]);
}
}
//console.log(order.toString());
order.sort().forEach( v => c.push( aOrig[v] ) );
console.log('---------');
c.forEach( v => console.log(v.toString()) );

How to remove NaN from a string in an array

I have this array that is used by Svg to create a map. It contains one big string. The problem is that there are NaNs in the array and it is not able to read the array properly. How can I remove these NaNs?
Array [
"M214.00002913287273,NaNL214.0000224099021,NaNL214.00002913287273,NaNL214.00002913287273,NaNL214.00011653149096,NaNL214.00011317000562,NaNL214.00011317000562,NaNL214.00000784346574,214.00018930549527L214.0000224099021,NaNL213.999936131779,213.99969560711412L213.999936131779,213.99969560711412L214.00011317000562,NaNL214.00002913287273 ...
]
array = ["M214.00002913287273,NaNL214.0000224099021,NaNL214.00002913287273,NaNL214.00002913287273,NaNL214.00011653149096,NaNL214.00011317000562,NaNL214.00011317000562,NaNL214.00000784346574,214.00018930549527L214.0000224099021,NaNL213.999936131779,213.99969560711412L213.999936131779,213.99969560711412L214.00011317000562,NaNL214.00002913287273"]
you can map this array and use replace for each string
array = array.map(x => x.replace(/NaN/g,''))
array = ["M214.00002913287273,NaNL214.0000224099021,NaNL214.00002913287273,NaNL214.00002913287273,NaNL214.00011653149096,NaNL214.00011317000562,NaNL214.00011317000562,NaNL214.00000784346574,214.00018930549527L214.0000224099021,NaNL213.999936131779,213.99969560711412L213.999936131779,213.99969560711412L214.00011317000562,NaNL214.00002913287273"]
array = array.map(x => x.replace(/NaN/g,''))
document.documentElement.innerHTML = array
you can map over the array & replace the cprrupted strings like this
const corruptedStrings = [
"M214.00002913287273,NaNL214.0000224099021,NaNL214.00002913287273..."
];
const replaceWord = (originalWord, wordToMatch, newValue) => (
originalWord.replace(new RegExp(wordToMatch, 'g'), newValue);
)
const cleanedStrings = corruptedStrings.map(str => replaceWord(str, 'NaN', ''));

Convert an array of string key pairs to an object

I have this data structure:
[
'ecl:hzl byr:1926 iyr:2010,pid:221225902 cid:61 hgt:186cm eyr:2021 hcl:#7d3b0c',
'hcl:#efcc98 hgt:178 pid:433543520,eyr:2020 byr:1926,ecl:blu cid:92,iyr:2010',
'iyr:2018,eyr:2026,byr:1946 ecl:brn,hcl:#b6652a hgt:158cm,pid:822320101'
]
I'm looking to convert those array values to objects instead of strings. I understand I need to do a map with a split(' '), but unsure of the logic inside of there.
Desired output:
[
{ecl: 'hzl', byr: 1926},
{hcl: '#efcc98', byr: 1926}
]
etc. with all of the fields.
I've tried:
.map(values => { let pair = values.split(':'); obj[pair[0]] = pair[1]; return obj })
But seem to get the same object repeated over and over, from the first index of the array.
If you're looking to get each element of the array as a separate object then try this:
const input = [
'ecl:hzl byr:1926 iyr:2010,pid:221225902 cid:61 hgt:186cm eyr:2021 hcl:#7d3b0c',
'hcl:#efcc98 hgt:178 pid:433543520,eyr:2020 byr:1926,ecl:blu cid:92,iyr:2010',
'iyr:2018,eyr:2026,byr:1946 ecl:brn,hcl:#b6652a hgt:158cm,pid:822320101'
]
const output = input.map((string) => { // for each string in array
const pairs = string.split(/[\ ,]/); // split by space or comma
const object = {}; // create an object
for (pair of pairs) { // for each pair in string
const parts = pair.split(":"); // split by colon
if (parts.length == 2) { // if you get 2 parts after splitting
object[parts[0]] = parts[1]; // use the first part as a key and the second as a value
}
}
return object;
});
console.log(output);
Try this
array = array.map(val => {
var obj = {}
val.split(' ').forEach(keyValPair => {
var keyVal = keyValPair.split(':')
obj[keyVal[0]] = keyVal[1];
})
return obj;
})
You can use Object.fromEntries.
const arr = [
'ecl:hzl byr:1926 iyr:2010,pid:221225902 cid:61 hgt:186cm eyr:2021 hcl:#7d3b0c',
'hcl:#efcc98 hgt:178 pid:433543520,eyr:2020 byr:1926,ecl:blu cid:92,iyr:2010',
'iyr:2018,eyr:2026,byr:1946 ecl:brn,hcl:#b6652a hgt:158cm,pid:822320101'
];
const res = arr.map(x => Object.fromEntries(x.replace(/,/g, ' ')
.split(' ').map(y => y.split(':'))));
console.log(res);

Convert a string of comma separated numbers into a 2D array

I have a string of numbers like so:
var original = "547,449,737,452,767,421,669,367,478,367,440,391,403,392,385,405,375,421,336,447";
And I wish to convert this string into a 2D array like so:
[[547, 449] [737, 452] [767, 421] [669, 367] [478, 367] [440, 391] [403, 392] [385, 405] [375, 421] [336, 447]]
But I'm having trouble doing it. I tried using regex:
var result = original.replace(/([-\d.]+),([-\d.]+),?/g, '[$1, $2] ').trim();
But the result was a string of the following and not an array:
[547, 449] [737, 452] [767, 421] [669, 367] [478, 367] [440, 391] [403, 392] [385, 405] [375, 421] [336, 447]
Might be easier to use a global regular expression to match two segments of digits, then split each match by comma and cast to number:
var original = "547,449,737,452,767,421,669,367,478,367,440,391,403,392,385,405,375,421,336,447";
const arr = original
.match(/\d+,\d+/g)
.map(substr => substr.split(',').map(Number));
console.log(arr);
You could use split and reduce methods with % operator to create the desired result.
var original = "547,449,737,452,767,421,669,367,478,367,440,391,403,392,385,405,375,421,336,447";
const result = original.split(',').reduce((r, e, i) => {
if (i % 2 == 0) r.push([]);
r[r.length - 1].push(e);
return r;
}, [])
console.log(result)
You could look for digits with a comma in between, replace, add brakets and parse as JSON.
var original = "547,449,737,452,767,421,669,367,478,367,440,391,403,392,385,405,375,421,336,447",
array = JSON.parse('[' + original.replace(/\d+,\d+/g, '[$&]') + ']');
console.log(array);
This could be a nice use case for using .matchAll():
var original = "547,449,737,452,767,421,669,367,478,367,440,391,403,392,385,405,375,421,336,447";
var array = Array.from(original.matchAll(/(\d+),(\d+)/g),
([, ...m]) => m.map(Number));
console.log(array);
Using Regex and JSON.parse are costlier. Do it using array to matrix as below
const original = "547,449,737,452,767,421,669,367,478,367,440,391,403,392,385,405,375,421,336,447";
const arrayToMatrix = (array, columns) => Array(Math.ceil(array.length / columns)).fill('').reduce((acc, cur, index) => {
return [...acc, [...array].splice(index * columns, columns)]
}, []);
const result = arrayToMatrix(original.split(','),2);
console.log(result);

How to convert string into two properties inside an array?

Here I am doing to convert the array into required format. output of parsedValues is ["abcdefgh(4034343), Mikhail(900002)"]
and Iam trying to convert it as ["abcdefgh(4034343)","Mikhail(900002)"]
How can I convert ["abcdefgh(4034343), Mikhail(900002)"] to ["abcdefgh(4034343)","Mikhail(900002)"] ?
private transformUser(userIdsString: any): string[] {
const parsedUserIdsArray = userIdsString;
console.log(parsedUserIdsArray);
const parsedValues = parsedUserIdsArray[4].userids;
console.log(parsedValues);
const splitValues = parsedValues.split(',');
console.log(splitValues);
const trimmedValues = splitValues.map(str => str.trim());
console.log(trimmedValues);
return trimmedValues;
}
The console.log(trimmedValues) is
(2) ["["abcdefgh(4034343)", "Mikhail(900002)"]"]
0: "["abcdefgh(4034343)"
1: "Mikhail(900002)"]"
length: 2
__proto__: Array(0)
Expected is :
(2) ["abcdefgh(4034343)", "Mikhail(900002)"]
0: "abcdefgh(4034343)"
1: "Mikhail(900002)"
length: 2
proto: Array(0)
You can use split on the string, to get an array from a separator (, in this case). If you have only one joined string, you can do...
["abcdefgh(4034343), Mikhail(900002), Someone(12934)"][0].split(', ')
To obtain a new array.
If the original array has multiple strings, you'll need to join all the arrays...
["abcdefgh(4034343), Mikhail(900002)", "Someone(12934)"]
.map(item => item.split(', '))
.reduce( (acc, item) => [...acc, ...item], [])
Try this
var input = ["abcdefgh(4034343), Mikhail(900002)"]
input.reduce(function(o,i){
var values = i.split(',');
if(values.length > 0){
o = o.concat(values);
}return o;},[]);
Output - ["abcdefgh(4034343)", " Mikhail(900002)"]
const trimmedValues = parsedValues[0].split(', ');

Categories

Resources