Is there way to change the index dynamically? or rebuild this object to where the 1 will be the Id of what ever object get passed into the function? Hope this makes sense.
export const createTree = (parentObj) => {
//keep in memory reference for later
const flatlist = { 1: parentObj }; <---- change the 1 based on parent.Id
...
}
My attempt thinking it would be easy as:
const flatlist = { parentObj.Id: parentObj };
Use computed property names to create a key from an expression:
const createTree = (parentObj) => {
const flatlist = { [parentObj.id]: parentObj };
return flatlist;
}
console.log(createTree({ id: 1 }));
Related
I'm working on a VueJS component that, among other things, can export data to .xlsx. For this, I'm using the json2xls library - so I need to pass to the json2xls() function an array of objects with identical keys (said keys will be column names)
This data I have to export is in an array of pretty deeply nested objects, though, so I need a function that will process that data to a form that will work with json2xls.
This is the method I'm using for that:
exportReport () {
const dataMap = []
this.reportPreview.forEach(elm => {
const auxObj = {}
auxObj.name = `${elm.client.first_name} ${elm.client.surname_1} ${elm.client.surname_2}`
elm.legal_files.forEach((e) => {
auxObj.legalfile = e.code
auxObj.actions = e.actions.count
dataMap.push(auxObj)
})
})
exportToXls(dataMap, `action-report-by-client-${this.options.start_date}-${this.options.end_date}.xlsx`)
}
If I do this, however, it appears that in cycles of elm.legal_files.forEach() the properties auxObj.legalfile and auxObj.actions are not overwritten, pushing several objects with identical values to dataMap
Why is this happening? What am I doing wrong? I'm hacking my way around this copying auxObj after "overwriting" the legalfile and actions properties and pushing the copy. This hack works, but I wonder what causes the first behavior and if there's a cleaner way around it.
exportReport () {
const dataMap = []
this.reportPreview.forEach(elm => {
const auxObj = {}
auxObj.name = `${elm.client.first_name} ${elm.client.surname_1} ${elm.client.surname_2}`
elm.legal_files.forEach((e) => {
auxObj.legalfile = e.code
auxObj.actions = e.actions.count
/*
If I just push auxObj to dataMap, the object is pushed with the same properties every time.
Copying auxObj and pushing the copy is a hack around this problem, but there may be a cleaner solution.
*/
const objCopy = { ...auxObj }
dataMap.push(objCopy)
})
})
exportToXls(dataMap, `action-report-by-client-${this.options.start_date}-${this.options.end_date}.xlsx`)
}
You pushed the same object every time.
exportReport() {
const dataMap = []
this.reportPreview.forEach(elm => {
const name = `${elm.client.first_name} ${elm.client.surname_1} ${elm.client.surname_2}`
elm.legal_files.forEach((e) => {
const auxObj = {} // Create a new object here
auxObj.name = name
auxObj.legalfile = e.code
auxObj.actions = e.actions.count
dataMap.push(auxObj) // Push it into the array
})
})
exportToXls(dataMap, `action-report-by-client-${this.options.start_date}-${this.options.end_date}.xlsx`)
}
New to react world, trying to learn destructuring, have been reading about it but stuck here,
if i do it like this function MList({action}) { // const data = [action];} i am just getting 'cameras'. So how to destructure and get same result as with props below
this is Mcard.js:
<Box pt={1}>
<MList
action="cameras"
/>
</Box>
This is inside MList komponent:
i want to destructure this code ( works gives 'name' and 'ident'):
function MList(props) {
const initialize = () => {
const data = props[props.action];
if (!data || data.length < 1) {
return;
}
data.map((e) => {
collapseStates["" + e.name + e.ident] = false;
return;
});
setCollapseS(collapseS);
};
}
I don't know React but destructuring the arguments should be something like the following
function MList({action, ...tail}) {
const initialize = () => {
const data = tail[action];
if (!data || data.length < 1) {
return;
}
data.map(({name, ident}) => {
collapseStates["" + name + ident] = false;
return;
});
setCollapseS(collapseS);
};
}
Also I would suggest using data.forEach instead of data.map if you don't need to save the result in another array
Nikita is correct about using props["action"] or props.action to grab the values. But you can actually destructure the props right inside of the function declaration like so:
function MList({ action, ...other props }) {
// Can now use action directly instead of props.action
}
It is also worth noting that array and object destructuring is not react specific, this is just how javascript works.
Edit: Accessing the action variable from here will give you "cameras" as a result because that is what you passed into the props
I want to create an object dynamically in typescript / javascript. I have an array reqParam in an object env that might look like this: env = {reqParams : ['fromTime', 'toTime']} and it is passed to my initialising function to build an obect dynamically
const myObject = _initObject(env.reqParams);
I've started the function, but I can't figure out how to get the key and values into the new object properly.
private _initObject(raqParams: any) {
let requestTemplate = {
bodyjson : "$util.escapeJavaScript($input.json('$'))",
"cognitoUserId": "$context.authorizer.claims.sub",
"cognitoUserEmail": "$context.authorizer.claims.email"
};
reqParams.forEach(param => {
// build new item
let templateEntry = "$input.params('`param`')";
// Put new item into object
requestTemplate[`param`] = templateEntry;
});
}
Hopefully, you can see what I'm trying to achieve. For example, here's the desired outcome for 2 reqParams : fromTime and toTime:
{
bodyjson : "$util.escapeJavaScript($input.json('$'))",
"fromTime": "$input.params('fromTime')",
"toTime": "$input.params('toTime')",
"cognitoUserId": "$context.authorizer.claims.sub",
"cognitoUserEmail": "$context.authorizer.claims.email"
}
1 typo and 2 fixes and it works, like so:
const _initObject = (reqParams) => {
let requestTemplate = {
bodyjson : "$util.escapeJavaScript($input.json('$'))",
"cognitoUserId": "$context.authorizer.claims.sub",
"cognitoUserEmail": "$context.authorizer.claims.email"
};
reqParams.forEach(param => {
// build new item
let templateEntry = `$input.params('${param}')`;
// Put new item into object
requestTemplate[param] = templateEntry;
});
return requestTemplate;
}
console.log(_initObject(['fromTime', 'toTime']));
reqParams.forEach(param => {
// build new item
let templateEntry = `$input.params('${param}')`;
// Put new item into object
requestTemplate[param] = templateEntry;
});
js use ${} for the string interpolation
key = 'dynamic'
object[key] = value
will give you a object of {'dynamic':value}
Hi i have parrent and child component. Parrent component is receiving data from server. This data are saved in state.data. Now, when i do action in child component, it should be call method from parrent controller. This is working now. Problem is inside this method which i am calling. I am receiving id as parameter. This data in parrent have list of items (packages) and every item has id. I need to update only one of them by id (or other way i don't know right way). Please how i can do it? I need to update isOpen state only that one item i open by clicking on button in child component
My method (but i am not sure if i started to do this right way), i stucked on this problem for while:
changeIsOpenState(typeOfPart: Number, id: Number) {
console.log(this.state.data.packages);
const selectedObject = this.state.data.packages.filter((obj) => {
const val= (obj.id === id) ? obj : false;
return val;
});
}
Array of data i want update (isOpen property).
what about immutably? I think u can use dot-prop-immutable package in this way:
const state = {
packages: [
{ isOpen: false, id: 1 },
{ isOpen: false, id: 2 },
{ isOpen: false, id: 3 }
]
};
const index = state.packages.findIndex(obj => obj.id === 3);
const newState = dotProp.set(state, `packages[${index}].isOpen`, true);
you could do it the ol' way :
changeIsOpenState(typeOfPart: Number, id: Number) {
// Copy the packages so you won't mumtate your state directly
const packages = Object.assign({}, ...this.StaticRange.data.packages);
// Get the package to edit and its index in the packages object
let packageIndex;
let packageToEdit;
for(let i = 0; i <= packages.length; i++){
if(packages[i].id === id){
packageIndex = i;
packageToEdit = packages[i];
packageToEdit.isOpen = true
}
}
packages[packageIndex] = packageToEdit;
setState({...this.state, data:{...this.state.data, packages}});
}
I did it like this:
1.I copy current data to another variable
2.Filter data by id
3.Save array key of item with same id
4. Change cloned value with negation
5. save new data to state
changeIsOpenState(typeOfPart: Number, id: Number) {
const subjectDataCopy = cloneDeep(this.state.data);
const keys = [];
subjectDataCopy.packages.filter((obj, key) => {
if (obj.id === id) {
keys.push(key);
}
});
subjectDataCopy.packages[keys[0]].isOpen = !subjectDataCopy.packages[keys[0]].isOpen;
this.setState({data: subjectDataCopy});
}
If there is better option to do this please let me know :)
The following image represents an object with two ui controls that are stored as this.state.controls
Initially the statesValue values are set via data that is received prior to componentDidMount and all is good. However updates to the each of the controls statesValues are sent via an event , which is handled with the following function
const handleValueStateChange = event => {
let controls = Object.entries(this.state.controls);
for (let cont of controls) {
let states = cont[1].states;
if (states) {
let state = Object.entries(states);
for (let [stateId, contUuid] of state) {
if (contUuid === event.uuid) {
cont[1].statesValue[stateId] = event.value;
}
}
}
}
};
which updates the values happily, however bearing in mind the updated values that change are a subset of this.state.controls, I have no idea how to use this.setState to update that that has been changed.
thanks in advance for any pointers
Instead of using Object.entries try destructuring to keep the reference to the objects.
And have a look at lodash. There are some nice helper functions to iterate over objects like mapValues and mapKeys. So you can keep the object structure and just replace the certain part. Afterwards update the whole state-object with the new one.
const handleValueStateChange = event => {
let {controls} = this.state;
controls = _.mapValues(controls, (cont) => {
const states = cont[1].states;
if (states) {
_.mapValues(states, (contUuid,stateId) => {
if (contUuid === event.uuid) {
cont[1].statesValue[stateId] = event.value;
}
});
}
return cont;
});
this.setState({controls});
};
Code is not tested but it should work like this.
Problem is you're updating an object which you've changed from it's original structure (by using Object.entries). You can still iterate in the same way however you'll need to update an object that maintains the original structure. Try this:
Make a copy of the controls object. Update that object. Replace it in state.
const handleValueStateChange = event => {
// copy controls object
const { controls } = this.state;
let _controls = Object.entries(controls);
for (let cont of _controls) {
let states = cont[1].states;
if (states) {
let state = Object.entries(states);
for (let [stateId, contUuid] of state) {
if (contUuid === event.uuid) {
// update controls object
controls[cont[0]].statesValue[stateId] = event.value;
}
}
}
}
}
// replace object in state
this.setState({controls});
};