How to turn a string onto a map? - javascript

I need to turn a string formatted like that:
string = "John:31,Miranda:28"
Onto this;
obj = { "John" => 31, "Miranda" => 28 }
I did this :
const class = new Map();
array = string.split(",");
And obviously I do not know what do with it because after the split I get something like this:
["John:31", "Miranda:28"]
And I don't know how to turn it onto an object (using the ":" as a arrow)... Maybe I don't need to use the array as an intermediary? Any thoughts? Thanks

You can use split to split by comma, and then map on the resulting strings to split again by colon, and feed the resulting array of arrays into the Map constructor.
For instance, if you want the map keyed by the names, which I suspect you do:
const string = "John:31,Miranda:28"
const map = new Map(string.split(",").map(entry => entry.split(":")));
console.log(map.get("John")); // "31" (a string)
If you want the numbers to be numbers, not strings, you'll need to convert them:
const string = "John:31,Miranda:28"
const map = new Map(string.split(",").map(entry => {
const parts = entry.split(":");
parts[1] = +parts[1];
return parts;
}));
console.log(map.get("John")); // 31 (a number)
My answer here goes into some detail on your options for converting from string to number.
If you want the map keyed by value instead (which I suspect you don't, but...), you just have to reverse the order of the inner array entries:
const string = "John:31,Miranda:28"
const map = new Map(string.split(",").map(entry => {
const [name, num] = entry.split(":");
return [num, name];
}));
console.log(map.get("31")); // John

So split on the commas, loop over it and split on the colon, and build the object.
var myString = "John:31,Miranda:28"
var myObj = myString.split(',').reduce(function (obj, part) {
var pieces = part.split(':')
obj[pieces[0]] = pieces[1]
return obj
}, {})

You could try something like this:
const data = "John:31,Miranda:28"
const splitData = data.split(',')
const result = splitData.reduce((newObject, item) => {
const [name, age] = item.split(':')
return {
...newObject,
[name]: parseInt(age)
}
}, {})
console.log(result)

I'll just add this here:
Basically, split string by the comma, then the colon.
Combine result into a map
const test = "John:31,Miranda:28";
console.log(test);
const obj = test.split(/,/).map(item => item.split(/:/));
console.log(obj);
const _map = new Map(obj);
console.log(_map);
console.log(_map.get("John"))

Related

How split string into separate variables based on several characters in Java Script

There is a String variable that comes value like the following.
"COMPANY=10^INVOICE_ID=100021^"
I need to get this into two variables like Company and InvoieId.
What will be possible ways to do that JS?
Here is a dynamic way. You can grab any value from obj.
const str = "COMPANY=10^INVOICE_ID=100021^"
const obj = {}
const strArr = str.split('^')
strArr.forEach(str => {
const [key, value] = str.split('=')
obj[key] = value
})
const {COMPANY, INVOICE_ID } = obj
console.log(INVOICE_ID, COMPANY)
We can also do it via regular expression
Regex101 demo
let str = `COMPANY=10^INVOICE_ID=100021^`
let regex = /(\w+)=\d+/g
let match = regex.exec(str)
while(match){
console.log(match[1])
match = regex.exec(str)
}
If this code will be called more than once, let's create a function:
const parseInput = (input) => {
const [company, invoice_id] =
input.split("^")
.map(kv => kv.split("=")[1]);
return {
company,
invoice_id
};
}

Replace words with array map

I have this array
(2) ['beginning=beginner', 'leaves=leave']
and this string
its beginner in the sounds leave
which i have converted to an array
var words = text.split(' ');
i want to replace beginner with beginning and leave with leaves it can be any dynamic words but for now it has only two elements i can replace it within for loop. Is it possible with map method.
this.words.map((words, i) => console.log(words));
Note: Only first instance should get replaced.
Any Solution Thanks
does this correct with your question ?
const arrString = ["beginning=beginner", "leaves=leave", "sound=sounds"];
let string = "its beginner in the sounds leave";
arrString.forEach((mapString) => {
const stringArr = mapString.split("=");
string = string.replace(stringArr[1], stringArr[0]);
});
console.log("string", string);
// "its beginning in the sound leaves"
You can do it in without a nested loop too if you compromise with space.
Here is a solution which creates a mapping object for replacement values and uses array methods like map(),forEach(),join() and string method like split()
const arrString = ["beginning=beginner", "leaves=leave", "sound=sounds"];
let string1 = "its beginner in the sounds leave beginner";
const replaceObj = {};
const arrBreaks = arrString.forEach(x => {
let els = x.split("=");
replaceObj[els[1]] = els[0]; });
const ans = string1.split(' ').map((x) => {
if(x in replaceObj) { let val = replaceObj[x]; delete val; return val; }
return x;
}).join(' ');
console.log(ans);

split matched array and unmatched array using Javascript / Node Js

I fetched data from database so its coming in string format and I want to check this string with my array data
my string values come like
const input = "fish.jpg\nanimal.jpg\nfish.pdf\nanimal.pdf\nmammal_bio.pdf\nfish_bio.jpg\nfruit_bio.pdf"
I want to compare this data with my array which contain
check=["mammal_bio.pdf","animal_bio.pdf","fruit_bio.pdf","tree_bio.pdf"]
So i want to compare all the array values which contain _bio.pdf and store them as
matchedArray=["mammal_bio.pdf","fruit_bio.pdf"]
unmatchedArray=["animal_bio.pdf","tree_bio.pdf"]
You can get matched and unmatched using Array.filter and String.split:
const input = "fish.jpg\nanimal.jpg\nfish.pdf\nanimal.pdf\nmammal_bio.pdf\nfish_bio.jpg\nfruit_bio.pdf";
const check = ["mammal_bio.pdf","animal_bio.pdf","fruit_bio.pdf","tree_bio.pdf"];
const inputArray = input.split("\n");
const matchedArray = check.filter(e => inputArray.includes(e));
const unmatchedArray = check.filter(e => !matchedArray.includes(e));
console.log(inputArray);
console.log(matchedArray);
console.log(unmatchedArray);
const input ="fish.jpg\nanimal.jpg\nfish.pdf\nanimal.pdf\nmammal_bio.pdf\nfish_bio.jpg\nfruit_bio.pdf"
const checkArray=["mammal_bio.pdf","animal_bio.pdf","fruit_bio.pdf","tree_bio.pdf"]
const matchedArray=checkArray.filter((e)=>input.split('\n').indexOf(e)!== -1);
const unmatchedArray=checkArray.filter((e)=>input.split('\n').indexOf(e)=== -1)
console.log(matchedArray, unmatchedArray);
Please note that input has a separator \n between filename
You can easily achieve this result using reduce with a single loop over the check array.
const input =
"fish.jpg\nanimal.jpg\nfish.pdf\nanimal.pdf\nmammal_bio.pdf\nfish_bio.jpg\nfruit_bio.pdf";
const check = [
"mammal_bio.pdf",
"animal_bio.pdf",
"fruit_bio.pdf",
"tree_bio.pdf",
];
const inputArr = input.split("\n");
const result = check.reduce((acc, curr) => {
if (inputArr.includes(curr)) acc[0].push(curr);
else acc[1].push(curr);
return acc;
},[[], []]);
const [matchedArray, unmatchedArray] = result;
console.log(matchedArray);
console.log(unmatchedArray);

Java script key value pair to object

I am new to javascript. I have an array of data in the format:
Toronto, Ontario: 95
Markham, Ontario: 71
I want to convert it to an array of object:
Like this, to be consistent with other functions.
I tried:
reportData.fbcity = Object.keys(reportData.city).map((city) => {
return {
city: city,
value: reportData.city[city]
};
});
What I get is:
{city: "Markham, Ontario": "value": 71}
Based on your updated question, I take it that you have this:
const start = ["Toronto, Ontario: 95", "Markham, Ontario: 71"];
and you want this:
result = [
{"Toronto, Ontario": 95},
{"Markham, Ontario": 71}
];
To do that, you need to split the number at the end of the string off, and then build objects with the two parts of the string. If you know there's only ever one :, then:
const result = start.map(str => {
const [city, number] = str.split(":");
return {
[city]: +number
};
});
Live Example:
const start = ["Toronto, Ontario: 95", "Markham, Ontario: 71"];
const result = start.map(str => {
const [city, number] = str.split(":");
return {
[city]: +number
};
});
console.log(result);
That uses destructuring to capture the two parts from split, then a computed property name to create a property with the city name, and + to coerce the number to number from string. (That's just one of your number-to-string options, see this answer for more options.)
reportData.fbcity = Object.keys(reportData.city).map((city) => {
return {
[city]: reportData.city[city]
};
})
You can use map and split
split with : and than build a object
+ is used to convert string to number
let data = ["Toronto, Ontario: 95", "Markham, Ontario: 71"];
let op = data.map(val=>{
let [key,value] = val.split(':')
return {[key]: +value}
})
console.log(op)

How to fetch a value from a string in javascript?

I want to fetch a particular value from a javascript string without using methods like indexOf or substr. Is there any predefined method of doing so?
For e.g., I have a string,
var str = "a=1|b=2|c=3|d=4|e=5|f=6";
I want to fetch the value of c from above string, how can I achieve it directly?
You can try with:
str.split('|').find(value => value.startsWith('c=')).split('=')[1]
You can also convert it into an object with:
const data = str.split('|').reduce((acc, val) => {
const [key, value] = val.split('=');
acc[key] = value;
return acc;
}, {});
data.c // 3
In this case, use split:
var str = "a=1|b=2|c=3|d=4|e=5|f=6";
var parts = str.split('|');
var value = parts[2].split('=')[1];
console.log(value);
Or maybe map it, to get all values to work with afterwards:
var str = "a=1|b=2|c=3|d=4|e=5|f=6";
var values = str.split('|').map(e => e.split('='));
console.log(values);
Using regex can solve this problem
const str = "a=1|b=2|c=3|d=4|e=5|f=6";
const matches = str.match(/c=([0-9]+)/);
console.log(matches[1]);
Ref:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
Try this -
var str = "a=1|b=2|c=3|d=4|e=5|f=6";
str.split('|')[2].split('=')[1];
You could turn that string into an associative array or an object
var str = "a=1|b=2|c=3|d=4|e=5|f=6";
var obj = {}; //[] for array
str.split("|").map(o => {
var el = o.split("=");
obj[el[0]] = el[1];
})
console.log(obj.a)
console.log(obj.b)
console.log(obj.c)
I suggest first splitting and mapping into some form of readable data structure. Finding by string is vulnerable to typos.
const mappedElements = str
.split('|')
.map(element => element.split('='))
.map(([key, value]) => ({ key: value }));
Array filter method can be memory efficient for such operation.
var cOutput = str.split('|').filter( (val) => {
const [k,v] = val.split('=');
return k=='c' ? v : false }
)[0].split('=')[1];
See Array Filter

Categories