React - How to Add Dynamic Key/Value Pair to an Object

Dynamic key with the value into the object into the react

You can create an object from selectedOrder.customer.dataObj looping on it's keys. Then use the [] notation to create a dynamic key, here the variable being the name of the key is x.

Array.reduce is a method that takes an initial state, here an empty object, then loop on the given array and execute a given function for every entry of the provided array. tmp here is an accumulator. It's value is the value returned by the last iteration of the reduce loop.

const selectedOrder = {  customer: {    dataObj: {      firstname: 'elon',      lastName: 'musk',      phoneNum: false,    },  },};
const obj = Object.keys(selectedOrder.customer.dataObj).reduce((tmp, x) => { tmp[x] = selectedOrder.customer.dataObj[x] || 'Error';
return tmp;}, {});
console.log(obj);

Dynamic Keys with array Values using UseState()

Your second version is close. It will work if map[key] is already set

But otherwise map[key] is undefined, and trying to spread [...undefined] will give you the not iterable error

You can first define the currentValues, and if none use an empty array

const addValueToMap = (key, newValue) => {
const currentValues = map[key] || []; // get current values for the key, or use empty array
setMap({ ...map, [key]: [...currentValues, newValue] })
}

React How to add new dynamic key to existing state?

Assuming response contains the first array in your OP:

getOrders(orders).then(response => {
const openedOrders = response.map(order => ({ ...order, open: true}))
this.setState({ openedOrders } )
})

response.map(order => ({ ...order, open: true}) adds a key open with the value true to every order in the array.

How do you dynamically update a key-value pair on a typed object in TypeScript

TLDR;

updateKey<K extends keyof X>(key: K, value: X[K]) {
dataToUpdate[key] = value;
}

Details:

Given

type X = {
prop: number;
other: string;
};

const dataToUpdate: X = {
prop: 1,
other: "string"
};

TypeScript does not allow us to access properties of a well-typed object with a known set of properties, such as your dataToUpdate, via an arbitrary property key type such as string.

As the language knows that the only keys of dataToUpdate are "prop" and "other", the key parameter of your update function must be restricted accordingly.

While we could write out the union type explicitly in the parameter list, key: "prop" | "other", this pattern is so fundamental to JavaScript that TypeScript provides the keyof type operator which produces a union type of all the property keys of a given type, allowing us to write

updateKey(key: keyof X, value: string | number) {
dataToUpdate[key] = value;
}

However, we're not done yet because the language needs to ensure that the type of the value parameter corresponds to the property type of the specified key and, as it happens, "prop" must be a number and "other" must be a string.

To describe this we adjust our declaration as follows

updateKey<K extends keyof X>(key: K, value: X[K])

What we've done is associate the types of the two parameters such that the type of value matches the type of the property specified by key, whenever the function is called.

React - how to add dynamic key/value pair to an object?

You can accomplish what you want using computed expression (I'm not really sure if you are trying to do that already). So your appendInput function should look something like this:

appendInput() {  var objectSize = Object.keys(this.state.milestonesValues).length;  var newInput = Object.assign({}, this.state.milestonesValues, {['milestone'+ objectSize]: ''});  this.setState({    milestonesValues: newInput)  });}

React: Dynamically adding and removing Key-Value pair from state object

I fixed my issue by first creating a new object with the current state and than deleting the key-value pair of the deleted field in the newly created object (newFormData). After that I set the newFormData as the current state.

The `delete``function only returns true/false so we have to create a new object and use that as the new state object to keep the data immutable.

<MinusCircleOutlined onClick={() => {remove(field.name); const newFormData = formData; delete newFormData[field.fieldKey]; setFormData(newFormData)}}/>


Related Topics



Leave a reply



Submit