How to split pipe separated string into array of object - javascript

I have pipe separated string (sshshhs , 1) | (ee23es , 1) , I want to split and make an array of object . Result must be like [ {name:sshshhs,value:1},{name:ee23es,value:2} ]. I am new to JavaScript could someone please help me .
Thanks

Check out this code snippet
let myString = "(sshshhs , 1) | (ee23es , 1)";
// extract only the elements
let stringList = myString .split(/\) \| \(|\(|\)/);
// remove first and last empty elements, due to regex
stringList = stringList.slice(1,-1);
//split each element into an object
let objList = stringList.map(s => {
const [name, value] = s.split(',').map(el => el.trim());
return { name, value };
})
In this way with one regex you get rid of pipe and parenthesis. Then with a map you extract the name and value from each element.

You have multiple ways to transform your string into an array of object
One of them could be to split multiple times and use reduce to make the object
"(sshshhs , 1) | (ee23es , 1)"
.split('|') // here we first split with the principal key
.map(e => {
return [e.replace(/\(|\)/g, '')] // we create an object of your values to reduce it
.reduce((result, token) => {
const [name, value] = token.split(',').map(e => e.trim()); // we get the key/values by splitting it (and trimming it by the same time)
return {name, value}; // we then return the finded name and value
}, {})
})
This is definitly not the most efficient way to do it, but it will help you understand the mechanics behind split and reduce and help you create your own solution

Related

JavaScript Split string and create new arrays

I have below string
"ITEM1","ITEM2","ITEM3","ITEM4","ITEM5","ITEM6","ITEM7"~100000000,1000048,0010041,1,1,1,1~100000001,1000050,,2,0,2,1~100000002,1068832,0010124,1,1,1,1~100000003,1143748,0010165,1,1,1,1~100000004,,0010173,1,2,1,1~100000005,,0010199,2,2,2,1~100000006,,0010215,1,2,1,1~100000007,,0010306,0,2,1,1~100000008,1092546,0010355,1,1,1,1~100000009,1037977,,2,1,2,1~
I need to split by ~ and should create separate arrays with double quotes "". Below is expected
[
["ITEM1","ITEM2","ITEM3","ITEM4","ITEM5","ITEM6","ITEM7"],
["100000000","1000048","0010041","1","1","1","1"],
["100000000","1000048","0010041","1","1","1","1"],
["100000000","1000048","0010041","1","1","1","1"],
]
This is what i have tried.
str.split('~').slice(2)
Which does not split to separate arrays. How to achieve the same. Thanks in Advance
You can first split with ~ and then split each sub array with ,. The code below is also removing the empty strings "". IF you want them included just remove the .filter(i => i)
EDIT:
removed the empty strings filter
const s = '"ITEM1","ITEM2","ITEM3","ITEM4","ITEM5","ITEM6","ITEM7"~100000000,1000048,0010041,1,1,1,1~100000001,1000050,,2,0,2,1~100000002,1068832,0010124,1,1,1,1~100000003,1143748,0010165,1,1,1,1~100000004,,0010173,1,2,1,1~100000005,,0010199,2,2,2,1~100000006,,0010215,1,2,1,1~100000007,,0010306,0,2,1,1~100000008,1092546,0010355,1,1,1,1~100000009,1037977,,2,1,2,1~'
const arr1 = s.split('~')
const arr2 = arr1.map(arr => {
arr = arr.replace(/\"/g, '')
return arr.split(',')
})
console.log(JSON.stringify(arr2, null, 2))

How to combine all the arrays which are inside another array and delete the last symbol in each word?

There is a 2 dimensional array:
let userGroup = [
['user1-', 'user2-', 'user3-'],
['user4-', 'user5-', 'user6-'],
['user7-', 'user8-', 'user9-']
];
How to make a single array from it and delete the symbol "-" after each element?
So the output will be: ['user1, 'user2', 'user3', 'user4', 'user5', 'user6', 'user7', etc...]
And also how to write a code which will do the same but with any number of inner arrays? For example if the "userGroup" array had more unexpected inner arrays with more users (['user11', 'user12', 'user13] etc.), what is the way to write a function which take the "userGroup" array and will do the same (delete the last element "-" in each element and combine all the elements in inner arrays into one array)?
Reduce is one way, can use also the new-ish flat method; by default it flattens only to single level but possible to define depth
userGroup.flat().map(item => item.slice(0, -1));
Try this:
console.log(userGroup.reduce((acc, curr)=> [...acc, ...curr], [])
.map(el => el.replace('-','')));
For a one liner, consider:
const mapped = userGroup.reduce((p,c) => p.concat(c), []).map(s => s.slice(0, s.length-1));
Try this
[].concat.apply([], userGroup).toString().split('-,');
Array.prototype.flat is the one you are looking for
userGroup.flat()
and then you will have the flat array for your array of arrays.
Then user the Array.prototype.map to convert the values as you like
userGroup.flat().map(m => m.replace('-', ''));
You need few things to achieve your goal.
.replace()
const u = 'user1-';
console.log(u.replace('-', ''));
.map()
const u = ["user1-", "user2-", "user3-"];
const m = u.map(i => i.replace("-", ""));
console.log(m);
.flat()
const u = [
["user1-", "user2-"],
["user3-", "user4-"]
];
console.log(u.flat());
So, combing all the 3 methods in a single statement, the below is the code:
let userGroup = [
['user1-', 'user2-', 'user3-'],
['user4-', 'user5-', 'user6-'],
['user7-', 'user8-', 'user9-']
];
let grouped = userGroup.flat().map(item => item.replace('-', ''));
console.log(grouped)

How to convert string in an array?

From http response I received an object like this:
{"[3, company1]":["role_user"], "[4, company2]":["role_admin"] }
The key is an array...Is there a way in typescript to convert the key
"[3, company1]"
in an array like this
[3, "company1"]
?
You can combine Object.keys with map and transform the string to array with split
let data = {"[3, company1]":["role_user"], "[4, company2]":["role_admin"] }
let keys = Object.keys(data)
.map(
el =>
el.replace('[', '')
.replace(']', '')
.split(',')
.map(el => el.trim())
.map(el => isNaN(parseFloat(el))
? el
: parseFloat(el))
)
console.log("Keys: ", keys)
Here is the fiddle:
https://jsfiddle.net/to38g6cb/1/
What do you want to convert the keys to?
if want to convert it to a normal array then the below should do.
const httpResponse = {
"[3, company1]": ["role_user"],
"[4, company2]": ["role_admin"]
};
const convertedKeys = Object.keys(httpResponse).map(value => {
let keyArray = value.replace("[", "").replace("]", "").split(", ");
return [parseInt(keyArray[0]), keyArray[1]];
});
console.log(convertedKeys);
If the above is not what you wanted, please kindly rephrase your question again.
You can remove the first and last character using slice(1,-1) and split the string at /\s*,\s*/ (comma with optional spaces on either side).
Then convert the first part to a number and return the array
const input = {
"[3, company1]": ["role_user"],
"[4, company2]": ["role_admin"]
}
const output = Object.keys(input).map(k => {
const [n, comp] = k.slice(1,-1).split(/\s*,\s*/)
return [+n, comp]
})
console.log(JSON.stringify(output))
It would have been easier if the company1 part were already quoted, so that you could just use JSON.parse. In fact, let's just do that! Put quotes around the company1 part with search and replace.
let key = `[3, company1]`;
let obj = JSON.parse(key.replace(/[$A-Z_]\w*/gi, '"$&"'))
console.log(obj);
Note: I'm guessing at what characters might be valid and went with something that looks vaguely like a JavaScript identifier. [$A-Z_]\w* Obviously not commas and right square brackets, due to deserialization ambiguity.

Array values to a string in loop

I have an object (key value pair) looks like this
I want to get a string of '[100000025]/[100000013]'
I can't use var str = OBJ[0].PC + OBJ[1].PC (which gives me '100000025100000013')
because I need the bracket structure.
The number of items can vary.
Added >> Can it be done without using arrow function?
const string = array.map(({PC}) => `[${PC}]`).join('/')
You could map every string to the string wrapped in brackets, then join that by slashes.
You can use a map() and a join() to get that structure. - this is hte same solution as Puwka's = but without the template literal.
var data = [
{am: 1, ct: "", pc: "1000000025"},
{am: 2, ct: "", pc: "1000000013"}
];
let newArr = data.map(item => "[" + item.pc +"]");
console.log(newArr.join("/")); // gives [1000000025]/[1000000013]
You can always use classic for in loop
let arr = [{PC:'1000'},{PC:'10000'}]
let arrOut = [];
for(let i = 0; i < arr.length; i++) {
arrOut.push('[' + arr[i].PC + ']');
}
now the arrOut is equal ["[1000]", "[10000]"] what we need is to convert it to a string and add '/' between items.
let str = arrOut.join('/');
console.log(str) // "[1000]/[10000]"
So you need a string in the format of: xxxx/yyyyy from a complex object array.
const basedata = [...];
const result = basedata.map( item => `[${item.PC}]` ).join('/')
so i will explain it now. The map function will return a new array with 1 entry per item. I state that I want PC, but i added some flavor using ticks to inject it inbetween some brackets. At this point it looks like: ["[1000000025]","[100000013]"] and then join will join the arrays on a slash, so it will turn into an array.
"[100000025]/[100000013]"
Now, this will expand based on the items in your basedata. So if you have 3 items in your basedata array, it would return:
"[10000000025]/[100000013]/[10000888]"
First if you want to divide the result then it will be better to change it into number and then just do the division.
Example
Number.parseInt("100000025")/Number.parseInt("100000013")
If you want to display it then better to use string interpolation
surround it with back tick
[${[0].PC}]/[${[1].PC}]
Hope this is what are you looking for

How to filter the array of object by matching all values instead of one

I am implementing a filter. it works fine. the problem is it's just matching a single object value instead of all value matching.
Matching means here is, let it be contain any single letter in the value
example: here is my object
{name:"D",color:"Green",size:50}
in case if i pass the filter object as :
let filter1 = {color:"Blu",size:'50'};
at present I am getting single result by matching size. But the color is not matching at all. so the result should be empty.
How to mach all values in the object and get the filtered value.
Live Demo
Code :
const nestedFilter = (targetArray, filters) => targetArray.filter(o => Object.keys(filters).find(k => filters[k].includes(o[k])));
let products = [
{name:"A",color:"Blue",size:70},
{name:"B",color:"Blue",size:60},
{name:"C",color:"Black",size:70},
{name:"D",color:"Green",size:50}
];
let filter1 = {color:"Blu",size:'50'};
console.log(nestedFilter(products, filter1));
Replace the .find invocation with .every. Be aware though that by using includes you expect your property values to be String.
If you want includes to work to other way round, so that the filter value can be a substring of the data, you should do:
const nestedFilter = (targetArray, filters) =>
targetArray.filter(o => Object.keys(filters).every(k =>
String(o[k]).includes(filters[k]))
)
)
The o[k] value needs to be converted to string, as otherwise you cannot apply includes to it (cf. size which is a number)
Check whether every of the Object.entries of the filter passed is equal to the same entry on the object being iterated over. If you want partial matches and are using different types of variables, it sounds like you also need to coerce them to strings first, so you can use .includes.
const nestedFilter = (targetArray, filters) => targetArray.filter(
obj => Object.entries(filters).every(
([key, val]) => String(obj[key]).includes(val)
)
);
let products = [
{name:"A",color:"Blue",size:70},
{name:"B",color:"Blue",size:60},
{name:"C",color:"Black",size:70},
{name:"D",color:"Green",size:50},
{name:"E",color:"Blu",size:'50'}
];
let filter1 = {color:"Blu",size:'70'};
console.log(nestedFilter(products, filter1));

Categories

Resources