How to convert JSON to URL params string as per my expected value? - arrays

I am working on an angular project. For a method getting a response JSON to convert stringify and POST a body to an API is done. Now the problem is for another one function I should send this value as a URL parameter I tried some ways but didn't get expected result. Please find the below codes and help me out. Thanks
Here is my JSON format value
const bodyJSON = [{FullPackageIDs:[11,7],
PartialPkg:[
{PackageID:4,
FormsList:[
{Form_Name:"Form name One"},
{Form_Name:"Form name Two"}]},
{PackageID:6,
FormsList:[
{Form_Name:"Form name Three"},
{Form_Name:"Form name Four"},
{Form_Name:"Form name Five"}
]
}
]
}]
My expected URL string value like below
http://localhost:4200/DownloadPackage?FullPackageIDs[0]=11&FullPackageIDs[1]=7&PartialPkg[0].PackageID=4&PartialPkg[0].FormsList[0].Form_Name=Form name One&PartialPkg[0].FormsList[1].Form_Name=Form name Two&PartialPkg[1].PackageID=6&PartialPkg[0].FormsList[0].Form_Name=Form name Three&PartialPkg[1].FormsList[1].Form_Name=Form name Four&PartialPkg[2].FormsList[2].Form_Name=Form name Five
I tried via forloop but didnt get expected result. Here is the code for what I tried.
for (let i = 0; i < getSelectedId.length; i++) {
fullPackageParams = `${fullPackageParams}FullPackageIDs[${i}]=${getSelectedId[i]}&`;
for (let j = 0; j < getPartialId.length; j++) {
// const getPartialName = this.partialPackage.map(res => res[i].FormsList);
const getPartialName = getPartialId[j].FormsList;
partialPackageIDParams = `${partialPackageIDParams}PartialPkg[${j}].PackageID=${getPartialId[j].PackageID}&`;
for (let index = 0; index < getPartialName.length; index++) {
partialPackageNameParams = `PartialPkg[${index}].FormsList[${index}].Form_Name=${getPartialName[index].Form_Name}&`;
}
}
}
console.log('params for full packages', fullPackageParams + partialPackageIDParams + partialPackageNameParams);

even if it seems kinda strange to me that you need to pass all of those params using query, you can try this
it just uses ES6 map, reduce functions to create your query string
let URLQuery = bodyJSON.map(value => {
const packageIDs = value.FullPackageIDs.map((v, i) => `FullPackageIDs[${i}]=${encodeURIComponent(v)}`);
const partialPkgs = value.PartialPkg.map((v, i) => {
const startKey = `PartialPkg[${i}]`;
return [
`${startKey}.PackageID=${v.PackageID}`
].concat(
v.FormsList.map((v, i) => `${startKey}.FormsList[${i}].Form_Name=${encodeURIComponent(v.Form_Name)}`)
);
}).reduce((arr, v) => {
return arr.concat(v)
}, []);
return packageIDs.concat(partialPkgs);
}).reduce((arr, v) => {
return arr.concat(v);
}, []).join("&");
const fullURL = `https://example.com?${URLQuery}`;

Related

Jest not generating values correctly using crypto

I made a function to generate a complex password using window.crypto lib, this work perfectly and return values like jQzPN%c#tr71ie6Dt^C8.
Here is my function :
const genPwd = (length: number): string => {
const regex = /^(?=.*[A-Z])(?=.*[!##$%^&*])(?=.*[0-9]).{8,}$/;
const charset =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~!##$%^&*()_-+={[}]|:;<,>.?/';
let result = '';
let values = new Uint32Array(length);
window.crypto.getRandomValues(values);
for (let i = 0; i < length; i++) {
result += charset[values[i] % charset.length];
}
if (!regex.test(result)) {
console.log('result', result);
return genPwd(length);
} else {
return result;
}
};
But when I try to test this function using Jest, it falls everytime in the last condition because it doesn't match the regex, the console.log shows "AAAAAAAAAAAAAAAAAAAA", like nothing is generating correctly, so it doesn't match the regex and looping.
Here is my test :
it('should generate a x length password', () => {
const mGetRandomValues = jest.fn().mockReturnValueOnce(new Uint32Array(20));
Object.defineProperty(globalThis, 'crypto', {
value: { getRandomValues: mGetRandomValues },
});
const valueToConvert = utils.genPwd(20);
const valueToFind = 20;
expect(valueToConvert).toHaveLength(valueToFind);
expect(mGetRandomValues).toBeCalledWith(new Uint32Array(valueToFind));
});
Does anyone have a solution ?
I have no idea about this issue

How to trim space from a property of an object present in an array of object?

I have an array of objects with me:
Array of objects
Now, I want to change the property name of an particular object(not the value). For ex:
My object has attribute PRODUCT NAME:'BAJAJ Brahmi Amla Hair Oil 300 ml' in my data.
Required result:
PRODUCT_NAME:'BAJAJ Brahmi Amla Hair Oil 300 ml'
So, how can I replace the space in my property to an '_'.
Language used: React.js
I tried this function but it's not working for my desired result:
const productList = () => {
for (let i = 0; i < data.length; i++) {
let obj = data[i];
console.log(obj);
Object.keys(obj).forEach((key) => {
var replacedKey = key.trim().toUpperCase().replace(/\s\s+/g, "_");
if (key !== replacedKey) {
obj[replacedKey] = obj[key];
delete obj[key];
}
});
}
};
Can somebody explain why is this not working ?
can you please change replace(/\s\s+/g, "_") to replace(" ", "_") and then try, as you can see the below code
const productList = () => {
for (let i = 0; i < data.length; i++) {
let obj = data[i];
console.log(obj);
Object.keys(obj).forEach((key) => {
var replacedKey = key.trim().toUpperCase().replace(" ", "_");
if (key !== replacedKey) {
obj[replacedKey] = obj[key];
delete obj[key];
}
});
}
};
const string = "PRODUCT NAME"
console.log(string.trim().toUpperCase().replace(" ", "_"))

Output variables one by one from array

how do I pull variables from array one by one? I want to make a card with one saying Zlin, second Praha, etc... The way it works now is that it outputs all of them at once 4x. Thank you.
const KartyLoop = () => {
var mesta = ['Zlin','Praha','Ostrava','Brno']
var lokace = []
for (var i=0; i < mesta.length; i++)
{
lokace += mesta + "\n"
}
return (<Text>{lokace}</Text>);
}
Your code pushes the array itself and not its values.
If I understand correctly you want to copy an array.
You would want to do this.
const KartyLoop = () => {
var mesta = ['Zlin','Praha','Ostrava','Brno']
var lokace = []
for (var i=0; i < mesta.length; i++)
{
lokace += mesta[i] + "\n"
}
return (lokace);
}

Combining a loop function and IF condition in google app scirpt

New to google app script and trying to create a function which combines loop (can be map, for or forEach) and IF condition.
See public spreadsheet for data: https://docs.google.com/spreadsheets/d/1V7CpCxBH0lg6wi1TAhfZJP5gXE8hj7ivQ8_ULxLSLgs/edit?usp=sharing
I wish to create an array inside a variable. In this array I want all quantity of column "D" but only if column "C" is "Buy".
This is the code I have tried but it comes back empty:
const ss = SpreadsheetApp.getActiveSpreadsheet();
const historySheet = ss.getSheetByName('Blad1');
function quantBuy () {
const searchRange = historySheet.getRange(3,2,historySheet.getLastRow()-1, 2)
let rangeValues = searchRange.getValues();
for (i = 0; i < historySheet.getLastRow()-1; i++) {
if (rangeValues[i] === 'Buy') {
console.log(i);
}}}
Any help is appreciated.
getValues is 2 demiensional
function quantBuy () {
const searchRange = historySheet.getRange(3,3,historySheet.getLastRow()-1, 2)
let rangeValues = searchRange.getValues();
for (let i = 0; i < rangeValues.length; i++) {
if (rangeValues[i][0] === 'Buy') {
console.log(rangeValues[i][1]);
}
}
}

PointCloud Component render issue fetch() custom data [react-three-fiber]

Based on a snippet of original r3f-example found in PointCloud.js
Tested by myself, this above original component is able to render pointcloud by pushing individual x y z value into the for-loop in Particle() function.
I modified it and added a `fetch()' method to retrieve a custom data txt file, snippet as shown below,
...
export function Particles() {
const [positions, colors] = useMemo(() => {
let positions = [], colors = []
positions.length = 3
colors.length = 3
const HEADER_SIZE = 4;
let stream, longArray, len;
let clusterCount ;
let xy_size ;
let clusterSize = [];
let XY_arr = [];
fetch(map)
.then((r) => r.text())
.then(text => {
stream = text.toString().split("\n"); // split by next line
longArray = stream.slice(2,); // remove header from main longArray
len = longArray.length;
for (let i = 0, count = 0; i < len; i += HEADER_SIZE ) {
xy_size = longArray.slice((i + HEADER_SIZE - 1), (i + HEADER_SIZE));
XY_arr.push(longArray.slice((i + HEADER_SIZE ), (i + HEADER_SIZE + xy_size*2)));
console.log(" Points in PointCloud " + count + ": " + xy_size );
clusterSize.push(xy_size);
clusterCount = count;
i += xy_size*2;
count ++;
}
for (let i = 0; i < (clusterCount-2); i++) {
for (let j = 0; j < clusterSize[i]*2; j+=2) {
positions.push( XY_arr[i][j] )
positions.push(0)
positions.push( XY_arr[i][j+1] )
colors.push(1)
colors.push(0.5)
colors.push(0.5)
console.log( XY_arr[i][j] );
}
}
}
)
return [new Float32Array(positions), new Float32Array(colors)]
}, [])
...
...
, map is the custom text file in string, with single data line-by-line
The fetch() method is able to read a custom pointcloud file into XY_arr as an object of Array(). I have checked that XY_arr[i][j] in the nested-forloop are able to return correct x and z value in console.
Current problem is that no pointcloud being rendered onto <Canvas />
Is the problem caused by position.push() nested loop being inside of 'fetch()' method ? And how to resolve. Thank you.
better use const [state, set] = useState() and then fetch in useEffect calling "set" when you're done. putting an async fetch request inside useMemo is practically a side-effect in the render function - which isn't good, nor will it work like that.

Resources