Parse to string a JS function as an Object value - javascript

Looking for a solution on parsing to string a JS function as an Object value.
All ideas are welcomed!
The final result would be a string config that i need to pass to a 3-rd party library (this is just a small part).
CodeSandBox Example
import { TEST } from "./config";
function objToString(obj) {
return Object.entries(obj).reduce((cstring, [key, value]) => {
// creates a string in the format 'key: value, key2: value2, etc...'
return cstring !== "" ? `${cstring}, ${key}: ${value}` : `${key}: ${value}`;
}, "");
}
export default function App() {
let configString = objToString({
onChangeBrand: function () {
const test = TEST.Success;
return test;
}
});
configString = `var configString = {
${configString}
}`;
console.log(configString);
return <p>configObj = `{configString}`</p>;
}
Current output
var configString = {
onChangeBrand: function () {
const test = _config.TEST.Success;
return test;
}
}
Desired output
var configString = {
onChangeBrand: function () {
const test = "success";
return test;
}
}

Not 100% sure but with a small change in onChangeBrand and the function call of aciConfig i think i've got your desired output:
import { TEST } from "./config";
function objToString(obj) {
return Object.entries(obj).reduce((cstring, [key, value]) => {
// creates a string in the format 'key: value, key2: value2, etc...'
return cstring !== "" ? `${cstring}, ${key}: ${value}` : `${key}: ${value}`;
}, "");
}
export default function App() {
const fun = () => {
const test = TEST.Success;
return test;
};
const vari = TEST;
const aciConfig = (v) => {
return {
onChangeBrand: function () {
const ss = v.Success.toString();
const rr = fun();
return {ss, rr}
}
};
};
let configObj = aciConfig(vari).onChangeBrand()
let configString = objToString(configObj);
console.log(typeof configObj.ss)
console.log(configObj.ss)
configString = `var configString = {
${configString}
}`;
console.log(configString);
return <p>configObj = `{configString}`</p>;
}

Related

JavaScript how replace function gets the value from spread syntax?

I have the following React code,
const useDynamicReplaceVariable = ({ label, formikValues, fieldsTypes }) => {
const { locale } = useTranslationState();
const formattedLabel = useMemo(() => {
const variablesRegex = /\?([\w-]+)\?/g;
let labelResult = label;
if (variablesRegex.test(label)) {
labelResult = ' ';
if (Object.keys(formikValues).length > 0) {
labelResult = label.replace(variablesRegex, (_, ...[variable]) => {
const type = fieldsTypes[variable];
// Set undefined or null to empty
let variableValue = (formikValues[variable] === undefined || formikValues[variable] == null) ? '' : formikValues[variable];
if (variableValue && [DesignerDdTypes.DatePicker, DesignerDdTypes.DatetimePicker].includes(type)) {
variableValue = dateToString(variableValue, locale, type === DesignerDdTypes.DatetimePicker);
}
return variableValue;
});
}
}
return labelResult;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [label, JSON.stringify(formikValues)]);
return { formattedLabel };
};
I can't understand the line labelResult = label.replace(variablesRegex, (_, ...[variable]), when no variable is defined, how come spread syntax is applied over it?
...[variable] is a shorthand for
function someFunction(...args) {
const [variable] = args
}
someFunction(1, 2, 3, 4, 5)
function someFunction(arg1, ...args) {
console.log('arg1', arg1)
console.log('args', args)
const [variable] = args
console.log('variable', variable)
}
someFunction(1, 2, 3, 4, 5)
function someFunction(arg1, ...[variable]) {
console.log('arg1', arg1)
console.log('variable', variable)
}

Set parameters from UI to SQL editor, React/JS

the idea of this stuff is that user can add parameters to the SQL editor from two inputs, one for the parameter itself and the other one for its value
and if user writes in SQL editor, automatically adds inputs that are the parameter and the value.
From SQL editor to inputs it works fine, cause I'm sending a regex. The trouble is located where I try to send the inputs to SQL Editor. I think is more like a logic problem, but I still don't find the solution.
The point is that by adding one parameter from the input, it adds more than required, even though I always clean it before adding, but apparently that doesn't affect.
This is the code
import React, { useEffect, useState} from 'react';
import SQLContainerInput from '../Components/SQLContainerInput';
........
function arrayParamsExec(stringSql) {
const paramsQueryText = [...stringSql.matchAll(/{{(\w+)}}/ig)];
const newArray = paramsQueryText.map(item => item[1]);
return newArray;
}
const initalStateCurrentChartInfo = {
SQLQuery: '',
dataType: 'TABLE',
columns: [],
};
const CustomSQLEditor = ({
fromQuery, // del Redux
}) = {
const [currentChartInfo, setCurrentChartInfo] = useState(
initalStateCurrentChartInfo,
);
const [params, setParams] = useState([]);
const [textSql, setTextSql] = useState('');
useEffect(() => {
....
let sqlDefaultString = '';
sqlDefaultString = fromQuery.internal_name
? `SELECT * FROM \`${fromQuery.internal_name}__${fromQuery.items[0]}\` LIMIT 20`
: '';
setCurrentChartInfo({
...currentChartInfo,
SQLQuery: `${sqlQuery}`,
});
},[fromQuery]);
// ------------------params---------------------
const addProperty = () => {
setParams([
...params,
{ name: '', value: '' },
]);
};
const updateProperty = (event, index, key) => {
const newProperties = [...params];
newProperties[index][key] = event?.target?.value;
// agregar parĂ¡metros al editor SQL
let sqlParams = textSql;
if (key === 'name') {
params.forEach(p => {
if (p.name && /^\w+$/i.test(p.name)) {
sqlParams += `{{${p.name}}}`;
}
});
setTextSql('');
setTextSql(`${sqlParams}`);
}
setParams(newProperties);
};
const deleteProperty = index => {
const newProperties = [...params];
newProperties.splice(index, 1);
const newTextSQL = replaceAll(textSql, `{{${params[index]?.name}}}`, '');
setTextSql(newTextSQL);
setParams(newProperties);
};
// ------------------end params---------------------
const changeTextEditor = (valueEditor) => {
const namesParams = arrayParamsExec(valueEditor);
const newProperties = namesParams.map((pName) => {
const valueNew = params.find(p => p.name === pName);
return {name: pName, value: valueNew?.value || ''};
});
setParams(newProperties);
setTextSql(valueEditor);
}
return (
<>
<SQLContainerInput
button={{
onClick: handleSubmit,
}}
input={{
value: `${textSql}\n`,
onChange: changeTextEditor,
}}
/>
<DymanicKeyValueInputInput
properties={params}
updateProperty={updateProperty}
deleteProperty={deleteProperty}
addProperty={addProperty}
/>
</>
);
}
Then, I tried as a solution set another value which is textSql, that takes care of placing the concatenated string, and the string coming from redux is fromQuery. The redux string is set in the sqlParams variable, when is added concatenates with the params and then, I clean textSql
......
const updateProperty = (event, index, key) => {
const newProperties = [...params];
newProperties[index][key] = event?.target?.value;
// agregar parĂ¡metros al editor SQL
let sqlParams = currentChartInfo.SQLQuery;
if (key === 'name') {
params.forEach(p => {
if (p.name && /^\w+$/i.test(p.name)) {
sqlParams += `{{${p.name}}}`;
}
});
setTextSql('');
setTextSql(`${sqlParams}`);
}
setParams(newProperties);
};
......
The trouble in there is that if I directly write from SQL editor, it resets the whole string, I mean, everything that has been written but there it works when I put the params and it's not repeated. I don't find a way to do that, so I'm sorry for the ignorance if I'm doing something wrong.
For example, when I write a large SQL text.
When a parameter is added from the input, it resets.
Video with the error demo: https://www.youtube.com/watch?v=rQBPOPyeXlI
Repo's url: https://gitlab.com/albert925/parametrosui-a-editor-sql
try this:
import { useState, useEffect } from 'react';
import DymanicKeyValueInputInput from './components/DymanicKeyValueInputInput';
import SQLContainerInput from './components/SQLContainerInput';
import { fromQuery } from './bd/data';
import { replaceAll, arrayParamsExec } from './utils/strings';
import { Content, ContentAddButton } from './stylesApp';
const initalStateCurrentChartInfo = {
SQLQuery: '',
columns: [],
};
function App() {
const [currentChartInfo, setCurrentChartInfo] = useState(
initalStateCurrentChartInfo,
);
const [params, setParams] = useState([]);
const [textSql, setTextSql] = useState('');
const [endSql, setendSql] = useState('');
useEffect(() => {
let sqlQuery = '';
sqlQuery = fromQuery.internal_name
? `SELECT * FROM \`${fromQuery.internal_name}__${fromQuery.items[0]}\` LIMIT 20`
: '';
setCurrentChartInfo({
...currentChartInfo,
SQLQuery: `${sqlQuery}`,
});
setTextSql(sqlQuery);
},[fromQuery]);
useEffect(()=>{
const endSql = replaceAll(textSql, '\n', '');
setendSql('')
setendSql(endSql);
},[textSql]);
const cleanSQLString = (string) => {
//corto la cadena en {{
//reemplazo {{ por "" en cada item
//devuelvo el array con los reemplazos
return string.split("{{").map(item=>item.replace("}}",""));
}
// ------------------params---------------------
const addProperty = () => {
setParams([
...params,
{ name: '', value: '' },
]);
};
const updateProperty = (event, index, key) => {
const newProperties = [...params];
newProperties[index][key] = event?.target?.value;
let currentSQL = cleanSQLString(endSql);
// clean the string so that then add parameters to sql
if (key === 'name' && /^\w+$/i.test(event?.target?.value)) {
let sqlParams;
if(currentSQL.length > 1){
sqlParams = `${currentSQL[0]}`;
}else{
sqlParams = `${endSql}`;
}
params.forEach(p => {
if (p.name && /^\w+$/i.test(p.name)) {
sqlParams += `{{${p.name}}}`;
}
});
setTextSql('');
setTextSql(`${sqlParams}`);
/*if(currentSQL.length > 1){
sqlParams = `${currentSQL[0]}`;
}else{
sqlParams = `${endSql}`;
}
console.log(sqlParams)
// get parameter positions by regular expression
const searchParamRegedix = arrayParamsExec(endSql);
console.log(searchParamRegedix, 'searchParamRegedix')
if (searchParamRegedix.paramsQueryText.length > 0) {
console.log(111)
// get the position
const searchPosition = searchParamRegedix.paramsQueryText[index]?.index;
// remove the old word in braces
const deleteOldParam = replaceAll(sqlParams, `${searchParamRegedix.list[index]}`, '');
// the remaining string is removed from the obtained position
const deleteFirtsLetter = deleteOldParam.substr(searchPosition + 2);
// the string is removed from the beginning to the position obtained
const deleteRemaining = deleteOldParam.substr(0, searchPosition + 2)
// the string of the beginning and end is combined with its parameter
const contantString = deleteRemaining + event?.target?.value + deleteFirtsLetter;
// the entire string is overwritten in the state
setTextSql(contantString);
}
else{
params.forEach(p => {
if (p.name && /^\w+$/i.test(p.name)) {
sqlParams += `{{${p.name}}}`;
}
});
setTextSql('');
setTextSql(`${sqlParams}`);
}*/
}
setParams(newProperties);
};
const deleteProperty = index => {
const newProperties = [...params];
newProperties.splice(index, 1);
const newTextSQL = replaceAll(textSql, `{{${params[index]?.name}}}`, '');
setTextSql(newTextSQL);
setParams(newProperties);
};
// ------------------end params---------------------
const changeTextEditor = (valueEditor) => {
const namesParams = arrayParamsExec(valueEditor);
// keep the value with the parameter with respect to adding a new parameter in the sql editor,
// but if the parameter word is changed, the value is deleted
const newProperties = namesParams.list.map((pName) => {
const valueNew = params.find(p => p.name === pName);
return {name: pName, value: valueNew?.value || ''};
});
setParams(newProperties);
setTextSql(valueEditor);
}
return (
<Content>
<div>
<SQLContainerInput
input={{
value: `${endSql}\n`,
onChange: changeTextEditor,
}}
/>
</div>
<div>
<h2>PARAMS</h2>
<ContentAddButton>
<DymanicKeyValueInputInput
properties={params}
updateProperty={updateProperty}
deleteProperty={deleteProperty}
addProperty={addProperty}
id="sqlapiparams"
className="isMultipleInpustSelects"
tilesColumns={["", ""]}
inputsPlaceholder={["My_Parameter", "Type params value"]}
isIconTransfer
isIconError
/>
</ContentAddButton>
</div>
</Content>
);
}
export default App;

Why the default value variable change as the changed variable value, Vuejs

as you see the code, on the handleUpdateFilter function the second "if" some how defaultCourseData is filtered as filteredData of the first "if". Thank you for helping me!
setup() {
const course = ref();
const defaultCourseData = null
const gettingCourse = async () => {
const { data } = await getCourse();
defaultCourseData = data
course.value = data;
};
const handleUpdateFilter = (data) => {
// data is filtering value
if (data.value.view) {
const filteredData = defaultCourseData.sort((a, b) => b.luotXem - a.luotXem);
course.value = filteredData;
}
if (!data.value.view) {
course.value = defaultCourseData // This case some how defaultCourseData filtered too
}
};
onMounted(() => {
gettingCourse();
});
return {
course,
handleUpdateFilter,
defaultCourseData
};
},
Your defaultCourseData variable isn't reactive.
Therefore it should be evaluated as null at every call.
Try this
defineComponent({
setup() {
const course = ref([]);
const defaultCourseData = ref([]);
const gettingCourse = async () => {
const { data } = await getCourse();
defaultCourseData.value = data
course.value = data;
};
const handleUpdateFilter = (data) => {
// data is filtering value
if (data.value.view) {
course.value = defaultCourseData.value.sort((a, b) => b.luotXem - a.luotXem);
}
if (!data.value.view) {
course.value = defaultCourseData.value // This case some how defaultCourseData filtered too
}
};
onMounted(async () => {
await gettingCourse();
});
return {
course,
handleUpdateFilter,
defaultCourseData
};
})
Edit: The actual issue here was, that the defaultCourseData always returned a sorted array as Array.prototype.sort() mutates the Array.
So making a copy solves the issue.
if (data.value.view) { course.value = [...defaultCourseData.value].sort((a, b) => b.luotXem - a.luotXem); }

How to map Array of Objects and return the length of each Object's value?

I want to check the value of every key in each object and write its length.
I tried doing this:
const a = [
{
name:"Bill",
age:'',
old:''
}
]
const myF = (arr) => {
return arr.map((i,k) => {
console.log(Object.keys(i))
return{ [Object.keys(i)]: ''}
})
}
console.log(myF(a))
I expect to get:
{
name:4,
age:0,
old:0
}
You can map it by taking entries. Let me know if this is what something you need:
var a = [ { name:"Bill", age:'', old:''}];
var result = a.map(obj=>Object.fromEntries(Object.entries(obj).map(([k,v])=>[k, v ? v : v.length])));
var result2 = a.map(obj=>Object.fromEntries(Object.entries(obj).map(([k,v])=>[k, v.length])));
console.log(result);
console.log(result2)
const a = [
{
name:"Bill",
age:'',
old:''
}
]
var b = a.map((x) =>{
if(x.age == '') {
x.age = 0;
}
if(x.old == '') {
x.old = 0;
}
return x;
})
console.log(b)

Return a modified new object from a function

what is the best practice to modify and return a new object from a function?
I wrote the following function :
export const addItemToCart = (currentCart, item) => {
const { name, ...otherProps } = item;
//if item exist in the cart
if (currentCart[name]) {
currentCart[name]["quantity"]++;
return currentCart;
}
//if the item does not exist
else
{
currentCart[name] = { ...otherProps };
currentCart[name]["quantity"] = 1;
return currentCart;
}
// the function must return a new modified object on each call
};
Obviously, the hard-coded property "quantity", and the return statements can definitely be improved.
how can I improve this function to be more readable?
More "readable" is very opinion-based, either way, you can try something like this:
const currentCart = {
hello: {
quantity: 1
}
};
const addItemToCart = (currentCart, item) => {
const { name } = item;
// Short circuit + return the last value
const quantityPrev = currentCart[name] && currentCart[name].quantity;
// Or operator on boolean expression
const quantity = 1 + (quantityPrev || 0);
// Destructing for shallow copy, dynamic key assign
return { ...currentCart, [name]: { quantity } };
};
console.log(addItemToCart(currentCart, { name: 'hello' }));
console.log(addItemToCart(currentCart, { name: 'blazer' }));

Categories

Resources