0

I have an object as below.

let data= {
  "" : { name: 'Tom', age: '21'},
  "26": { name: 'Harry', age: '22'}
}

The first entry in the list is created when a user clicks on add button to add a new entry. I take the key value for the first entry from the input field. So if the input value is 8 the new data should be like below.

let data= {
  "8" : { name: 'Tom', age: '21'},
  "26": { name: 'Harry', age: '22'}
}

How can I achieve that?

3
  • So how come you first had key ""? Commented Jan 27, 2021 at 19:23
  • Its just that I am initializing it like that in my react state when a new field is added. So later when the user will put value in the field I want that value to replace there. Commented Jan 27, 2021 at 19:26
  • I would store the value in a different state property until you have the key, and only then add the pair to the object. Commented Jan 27, 2021 at 19:31

2 Answers 2

1

You can generate the new state using destructuring, and then setting the new state:

const updateTempKey = ({ '': temp, ...data }, input) => ({
  ...data,
  [input]: temp
})

const state = {
  "" : { name: 'Tom', age: '21'},
  "26": { name: 'Harry', age: '22'}
}

const newState = updateTempKey(state, '8') 

console.log(newState)

Whenever the input is set, you can also set the state of the data:

setData(state => updateTempKey(state, input))
Sign up to request clarification or add additional context in comments.

Comments

0

You can set data['some_key'] to be equals data[''], than delete data[''] like below (according to your example):

data['8'] = data['']
delete data['']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.