How do I convert a string to a dictionary in javascript? - javascript

I have a string
var str = "1:6,5,2,2:3";
I want to convert this str into a js dictionary such that:
var dict = {1:"6,5,2",
2:"3"};
so that I can fetch the values by their respective key index. How do I convert it?
I had tried this code to store the splitted values into an array:
var pages = "1:6,5,2,2:3";
var numbers = [];
if (pages.includes(',')) {
page_nos = pages.split(',');
for (var i = 0; i < page_nos.length; i++) {
if (page_nos[i].includes(':')) {
var n = page_nos[i].split(':');
numbers.push(n[1]);
} else {
numbers.push(page_nos[i]);
}
}
} else {
page_nos = pages.split(':');
numbers.push(page_nos[1])
};
console.log('numbers: ', numbers);
But it's incorrect, as without dictionary it's impossible to know what value belongs to which index

If you cannot make your input string a proper JSON or another easily parsable format in the first place, this answers your question:
const str = "1:6,5,2,2:3";
const obj = str.split(/,(?=\d+:)/).reduce((accu, part) => {
const [k, v] = part.split(':', 2);
accu[k] = v;
return accu;
}, {});
console.log(obj);
Cut the string at all commas that are followed by digits and a colon. Each part has a key in front of a colon and a value after it, which should be stuffed in an object in this format.

No mutations solution.
const str = "1:6,5,2,2:3";
const dict = str
.split(/(\d+:.*)(?=\d+:)/g)
.reduce((t, c) => {
const [key, value] = c.replace(/,$/, "").split(/:/);
return { ...t, [key]: value }
});
console.log(dict);

if you consider not using regular expression, you might try this as well.
to take out a dict (Object) from that string, this will do.
var pages = "1:6,5,2,2:3";
function stringToObject(str) {
var page_object = {};
var last_object;
str.split(",").forEach((item) => {
if (item.includes(":")) {
page_object[item.split(":")[0]] = item.split(":")[1];
last_object = item.split(":")[0];
} else {
page_object[last_object] += `,${item}`;
}
});
return page_object;
}
console.log(stringToObject(pages))

Presented below may be one possible solution to achieve the desired objective.
NOTE:
In lieu of var the code uses either let or const as applicable.
Code Snippet
const pages = "1:6,5,2,2:3";
const resObj = {};
let page_nos, k;
if (pages.includes(',')) {
page_nos = pages.split(',');
for (let i = 0; i < page_nos.length; i++) {
if (page_nos[i].includes(':')) {
let n = page_nos[i].split(':');
k = n[0];
resObj[k] = n[1].toString();
} else {
resObj[k] += ", " + page_nos[i].toString();
}
}
} else {
page_nos = pages.split(':');
resObj[page_nos[0]] = [page_nos[1]]
numbers.push(page_nos[1])
};
console.log('result object: ', resObj);
This code essentially fixes the code given in the question. It is self-explanatory and any specific information required may be added based on questions in comments.

You could take nested splitring for entries and get an object from it.
const
str = "1:6,5,2,2:3",
result = Object.fromEntries(str
.split(/,(?=[^,]*:)/)
.map(s => s.split(':'))
);
console.log(result);

Related

I have a array of string have to find all the common character present from all strings

I have a array of string.
let arr=["robin","rohit","roy"];
Need to find all the common character present in all the strings in array.
Output Eg: r,o
I have tried to create a function for above case with multiple loops but i want to know what should be the efficient way to achive it.
Here's a functional solution which will work with an array of any iterable value (not just strings), and uses object identity comparison for value equality:
function findCommon (iterA, iterB) {
const common = new Set();
const uniqueB = new Set(iterB);
for (const value of iterA) if (uniqueB.has(value)) common.add(value);
return common;
}
function findAllCommon (arrayOfIter) {
if (arrayOfIter.length === 0) return [];
let common = new Set(arrayOfIter[0]);
for (let i = 1; i < arrayOfIter.length; i += 1) {
common = findCommon(common, arrayOfIter[i]);
}
return [...common];
}
const arr = ['robin', 'rohit', 'roy'];
const result = findAllCommon(arr);
console.log(result);
const arr = ["roooooobin","rohit","roy"];
const commonChars = (arr) => {
const charsCount = arr.reduce((sum, word) => {
const wordChars = word.split('').reduce((ws, c) => {
ws[c] = 1;
return ws;
}, {});
Object.keys(wordChars).forEach((c) => {
sum[c] = (sum[c] || 0) + 1;
});
return sum;
}, {});
return Object.keys(charsCount).filter(key => charsCount[key] === arr.length);
}
console.log(commonChars(arr));
Okay, the idea is to count the amount of times each letter occurs but only counting 1 letter per string
let arr=["robin","rohit","roy"];
function commonLetter(array){
var count={} //object used for counting letters total
for(let i=0;i<array.length;i++){
//looping through the array
const cache={} //same letters only counted once here
for(let j=0;j<array[i].length;j++){
//looping through the string
let letter=array[i][j]
if(cache[letter]!==true){
//if letter not yet counted in this string
cache[letter]=true //well now it is counted in this string
count[letter]=(count[letter]||0)+1
//I don't say count[letter]++ because count[letter] may not be defined yet, hence (count[letter]||0)
}
}
}
return Object.keys(count)
.filter(letter=>count[letter]===array.length)
.join(',')
}
//usage
console.log(commonLetter(arr))
No matter which way you choose, you will still need to count all characters, you cannot get around O(n*2) as far as I know.
arr=["robin","rohit","roy"];
let commonChars = sumCommonCharacters(arr);
function sumCommonCharacters(arr) {
data = {};
for(let i = 0; i < arr.length; i++) {
for(let char in arr[i]) {
let key = arr[i][char];
data[key] = (data[key] != null) ? data[key]+1 : 1;
}
}
return data;
}
console.log(commonChars);
Here is a 1 liner if anyone interested
new Set(arr.map(d => [...d]).flat(Infinity).reduce((ac,d) => {(new RegExp(`(?:.*${d}.*){${arr.length}}`)).test(arr) && ac.push(d); return ac},[])) //{r,o}
You can use an object to check for the occurrences of each character. loop on the words in the array, then loop on the chars of each word.
let arr = ["robin","rohit","roy"];
const restWords = arr.slice(1);
const result = arr[0].split('').filter(char =>
restWords.every(word => word.includes(char)))
const uniqueChars = Array.from(new Set(result));
console.log(uniqueChars);

How create two dimensional (2D) string array dynamic in JavaScript

If the word is ABC
A[0][0]="AA" A[0][1]="AB" A[0][2]="AC"
A[1][0]="BA" A[1][1]="BB" A[1][2]="BC"
A[2][0]="CA" A[2][1]="CB" A[2][2]="CC"
using for, string or array method.
const a = [..."ABC"];
console.log(
a.map(l => a.map(c => l + c))
);
An odd request. Is this what you are looking for?
const word = "ABC";
const letters = word.split("");
const array = [];
letters.forEach((letter1,index1) => {
letters.forEach((letter2,index2) => {
if (!array[index1]) {
array[index1] = [];
}
array[index1][index2] = letter1+letter2;
});
});
console.log(array);
UPDATE:
Another version using older Javascript. Also, check out Asaf's solution using a more functional approach below, is very elegant.
var word = "ABC";
var letters = word.split("");
var array = [];
for(var index1 = 0;index1!==letters.length;index1++) {
for(var index2 = 0;index2!==letters.length;index2++) {
if (!array[index1]) {
array[index1] = [];
}
array[index1][index2] = letters[index1]+letters[index2];
}
}
console.log(array);

Convert string to JSON stringformat

I have a string where the object name is separated by dot from the field name as follows:
{\"person.firstName\":\"Ahmed\",\"person.job\":\"Doctor\",\"products.packName\":\"antibiotic\",\"products.packSize\":\"large\"}}";
I want to parse it to look like the json format:
"{\"person\": {\"firstName\":\"Ahmed\",\"job\":\"Doctor\",},\"products\": {\"packName\":\"antibiotic\",\"packSize\":\"large\"}}";
Is there an efficient algorithm for that?
Maybe this is help for you.
var str='{\"person.firstName\":\"Ahmed\",\"person.job\":\"Doctor\",\"products.packName\":\"antibiotic\",\"products.packSize\":\"large\"}';
var newObj={}
var json=JSON.parse(str);
for (i in json) {
var splt=i.split('.');
var key=splt[0];
var subkey=splt[1];
if(!(key in newObj)) {
newObj[key]={};
}
newObj[key][subkey]=json[i];
}
//if you need string use str or not use newObj
var str=JSON.stringify(newObj);
console.log(str);
console.log(newObj);
console.log(newObj.person);
console.log(newObj.person.firstName);
console.log(newObj.person.job);
Assuming left side may have multiple dots
let parsedObj = JSON.parse(<..YOUR STRINGIFIED JSON..>);
let myObj = {};
Object.keys(parsedObj).forEach((key) => {
let val = parsedObj[key];
let subKeys = key.split(".");
let currentRef = myObj;
subKeys.forEach((subKey, idx) => {
if(idx === subKeys.length - 1) {
currentRef[subKey] = val;
} else {
currentRef[subKey] = currentRef[subKey] || {};
currentRef = currentRef[subKey];
}
});
});
let finalString = JSON.stringify(myObj);
P.S. Your string seems to contain an extra } in the end

what is the best way to extract variables with '=' from a string in javascript

I want to extract the variables names from a string like this: "foo=valor bar=second", and so on.
To return:
{
foo: "valor",
bar: "second",
...
}
You can use Regex Look Aheads to check for a variable name that is preceded by an = symbol
var str = "foo=valor bar=second";
var varRegex = /\w+(?=(\s)*(\=))/g;
var valueRegex = /(?<=(\=)[\s'"]*)\w+/g;
var varArr = str.match(varRegex);
var valueArr = str.match(valueRegex);
console.log(valueArr);
let obj = {};
for(let i in varArr) {
obj[varArr[i]] = valueArr[i];
}
console.log(obj);
var str = "foo=valor,bar=second";
var obj = {};
str.split(",").forEach(
function(item){
if(item){
var vars = item.split("=");
obj[vars[0]] = vars[1]
}
});
console.log(obj)
Different approach from the previous answer: You can split the string on spaces and then map the result array, splitting on the equal sign to create your object (left side is property, right side is value)
If you need it your specific format you can reduce it to convert the array into one big object with all the values
let a = "foo=valor bar=second"
console.log(a.split(' ').map((i,v) => { return JSON.parse(`{"${i.split('=')[0]}": "${i.split('=')[1]}"}`);}))
let b = a.split(' ').map((i,v) => { return JSON.parse(`{"${i.split('=')[0]}": "${i.split('=')[1]}"}`);})
console.log(b.reduce(function(acc, x) {
for (var key in x) acc[key] = x[key];
return acc;
}));
Not necessarily the quickest answer (in terms of speed of submission), but less regular expressions to maintain and less variables to store.
function toJSON(str) {
const regex = /(\w+)\=(\w+)\s*/g;
let result = {};
let match;
while (match = regex.exec(str)) {
result[match[1]] = match[2];
}
return result;
}
console.log(toJSON("foo=valor bar=second"));

javascript - retrieve string right after a specific string and before the next colon

I'm a beginner in learning javascript, need to retrieve a specific part of value from the string.
below is the format of string provided by my teammates, they are a set of parameter and its value separated by a colon.
how can I retrieve the value, once input the parameter name, then return the value just before the next colon?
string = "productCat:Wine:country:Australia:year:2000:type:white wine:"
example:
if input 'productCat', then return 'Wine'
if input 'country', then return 'Australia'
if input 'year', then return '2000'
if input 'type', then return 'white wine'
thanks!
Here's an example that will be compatible with older browsers.
var string = "productCat:Wine:country:Australia:year:2000:type:white wine:"
function getPart(string, input) {
var parts = string.split(":");
for (var i = 0; i < parts.length; i = i + 2) {
if (parts[i] == input) {
return parts[i+1];
}
}
}
console.log(getPart(string, "productCat"));
First split your string into array of strings using split() function
string="productCat:Wine:country:Australia:year:2000:type:white wine:"
var array=string.split(":");
Second according to input return the value which is index+
return var x=array[array.indexOf(input)+1];
Here is a small example. Just split the string, then look for the next index if something is found.
But this is not very smart.
const string = 'productCat:Wine:country:Australia:year:2000:type:white wine';
const findNext = (data, str) => {
const array = data.split(':');
const i = array.indexOf(str);
if(i >= 0) return array[i+1];
}
console.log(findNext(string, 'productCat'));
console.log(findNext(string, 'country'));
Here is what I would do if I were you:
const string = 'productCat:Wine:country:Australia:year:2000:type:white wine';
const parseString = str => {
const array = str.split(':');
const result = {};
for(let i = 0; i<array.length; i=i+2) {
result[array[i]] = array[i+1];
}
return result;
}
const result = parseString(string);
console.log(result);
console.log(result.country);
console.log(result.year);
Just parse the string and build an object you'll use easily later ;)

Categories