How to edit/update an object in an array and keep all other nested data?
I am trying to update purely just the firstName, lastName and profile for an object without destroying any other data within that object...
Here's an example of the current state.
state = {
children: [
{
id: 1,
firstName: 'Bella',
lastName: 'Laupama',
profile: 'child_care',
schedules: [
{
id: 1,
date: '25 December, 2018',
parent: 'Chris',
activity: 'Christmas'
},
{
id: 2,
date: '28 December, 2018',
parent: 'Mischa',
activity: 'Christmas with Malane Whanau'
},
{
id: 3,
date: '31 December, 2018',
parent: 'Laura',
activity: 'New Years Eve'
},
{
id: 4,
date: '1 January, 2019',
parent: 'Laura',
activity: 'New Years Day'
}
]
}
]
}
And here's the current function I'm trying to pass it to update the current state...
editChild = (first, last, prof) => {
var updatedChild = {
firstName: first,
lastName: last,
profile: prof
}
var children = this.state.children
for (var i = 0; i < children.length; i++) {
if (children[i].firstName === first) {
children[i] = updatedChild
}
}
this.setState({ children })
}
**UPDATE**
Here's the code where I'm calling the function ( from a child component )
export default class EditChild extends React.Component {
state = {
firstName: '',
lastName: '',
profile: '',
}
handleChange = e => {
this.setState({
[e.target.name]: e.target.value
})
}
submitHandler = e => {
e.preventDefault()
this.props.editChild(this.state.firstName, this.state.lastName, this.state.profile)
// Final validation before submitting to server
console.log('SUBMITTED:', this.state)
// Clear the state to clear the form
this.setState({
firstName: '',
lastName: '',
profile: ''
})
}
...form etc is in the render etc...
The form works fine and console logs the result like this:
SUBMITTED:
{firstName: "Donald", lastName: "Trump", profile: "face"}
UPDATE
Thank you to @Tholle and @charlietfl for leading me in the right direction. Basically I needed to be passing the ID as well, and not trying to match based off the first name, as the first name is obviously something that can be changed from the edit form as well. So if I changed Bella Laupama to Charlie Chaplan, it wouldn't find the id.
So I used @Tholle code and modified it to search and replace by id and it worked perfectly :)
editChild = (id, first, last, prof) => {
var updatedChild = {
firstName: first,
lastName: last,
profile: prof
}
this.setState(prevState => {
const children = [...prevState.children]
const childIndex = children.findIndex(child => child.id === id)
children[childIndex] = { ...children[childIndex], ...updatedChild }
return { children }
})
console.log(this.state)
}
javascript reactjs
add a comment |
I am trying to update purely just the firstName, lastName and profile for an object without destroying any other data within that object...
Here's an example of the current state.
state = {
children: [
{
id: 1,
firstName: 'Bella',
lastName: 'Laupama',
profile: 'child_care',
schedules: [
{
id: 1,
date: '25 December, 2018',
parent: 'Chris',
activity: 'Christmas'
},
{
id: 2,
date: '28 December, 2018',
parent: 'Mischa',
activity: 'Christmas with Malane Whanau'
},
{
id: 3,
date: '31 December, 2018',
parent: 'Laura',
activity: 'New Years Eve'
},
{
id: 4,
date: '1 January, 2019',
parent: 'Laura',
activity: 'New Years Day'
}
]
}
]
}
And here's the current function I'm trying to pass it to update the current state...
editChild = (first, last, prof) => {
var updatedChild = {
firstName: first,
lastName: last,
profile: prof
}
var children = this.state.children
for (var i = 0; i < children.length; i++) {
if (children[i].firstName === first) {
children[i] = updatedChild
}
}
this.setState({ children })
}
**UPDATE**
Here's the code where I'm calling the function ( from a child component )
export default class EditChild extends React.Component {
state = {
firstName: '',
lastName: '',
profile: '',
}
handleChange = e => {
this.setState({
[e.target.name]: e.target.value
})
}
submitHandler = e => {
e.preventDefault()
this.props.editChild(this.state.firstName, this.state.lastName, this.state.profile)
// Final validation before submitting to server
console.log('SUBMITTED:', this.state)
// Clear the state to clear the form
this.setState({
firstName: '',
lastName: '',
profile: ''
})
}
...form etc is in the render etc...
The form works fine and console logs the result like this:
SUBMITTED:
{firstName: "Donald", lastName: "Trump", profile: "face"}
UPDATE
Thank you to @Tholle and @charlietfl for leading me in the right direction. Basically I needed to be passing the ID as well, and not trying to match based off the first name, as the first name is obviously something that can be changed from the edit form as well. So if I changed Bella Laupama to Charlie Chaplan, it wouldn't find the id.
So I used @Tholle code and modified it to search and replace by id and it worked perfectly :)
editChild = (id, first, last, prof) => {
var updatedChild = {
firstName: first,
lastName: last,
profile: prof
}
this.setState(prevState => {
const children = [...prevState.children]
const childIndex = children.findIndex(child => child.id === id)
children[childIndex] = { ...children[childIndex], ...updatedChild }
return { children }
})
console.log(this.state)
}
javascript reactjs
Just matching first names seems very flaky since in general first names aren't unique. Don't you have a reference to the original object at the time you are editing it? Show how you useeditChild()
– charlietfl
Nov 21 '18 at 23:13
if you do a console.log afterif (children[i].firstName === first)
, do you get something when you would expect it? Also I don't think this is what you want... this would remove theschedules
andid
properties.
– Katie.Sun
Nov 21 '18 at 23:13
@charlietfl I just updated the post to show the editChild() in action.
– Tearz
Nov 21 '18 at 23:31
add a comment |
I am trying to update purely just the firstName, lastName and profile for an object without destroying any other data within that object...
Here's an example of the current state.
state = {
children: [
{
id: 1,
firstName: 'Bella',
lastName: 'Laupama',
profile: 'child_care',
schedules: [
{
id: 1,
date: '25 December, 2018',
parent: 'Chris',
activity: 'Christmas'
},
{
id: 2,
date: '28 December, 2018',
parent: 'Mischa',
activity: 'Christmas with Malane Whanau'
},
{
id: 3,
date: '31 December, 2018',
parent: 'Laura',
activity: 'New Years Eve'
},
{
id: 4,
date: '1 January, 2019',
parent: 'Laura',
activity: 'New Years Day'
}
]
}
]
}
And here's the current function I'm trying to pass it to update the current state...
editChild = (first, last, prof) => {
var updatedChild = {
firstName: first,
lastName: last,
profile: prof
}
var children = this.state.children
for (var i = 0; i < children.length; i++) {
if (children[i].firstName === first) {
children[i] = updatedChild
}
}
this.setState({ children })
}
**UPDATE**
Here's the code where I'm calling the function ( from a child component )
export default class EditChild extends React.Component {
state = {
firstName: '',
lastName: '',
profile: '',
}
handleChange = e => {
this.setState({
[e.target.name]: e.target.value
})
}
submitHandler = e => {
e.preventDefault()
this.props.editChild(this.state.firstName, this.state.lastName, this.state.profile)
// Final validation before submitting to server
console.log('SUBMITTED:', this.state)
// Clear the state to clear the form
this.setState({
firstName: '',
lastName: '',
profile: ''
})
}
...form etc is in the render etc...
The form works fine and console logs the result like this:
SUBMITTED:
{firstName: "Donald", lastName: "Trump", profile: "face"}
UPDATE
Thank you to @Tholle and @charlietfl for leading me in the right direction. Basically I needed to be passing the ID as well, and not trying to match based off the first name, as the first name is obviously something that can be changed from the edit form as well. So if I changed Bella Laupama to Charlie Chaplan, it wouldn't find the id.
So I used @Tholle code and modified it to search and replace by id and it worked perfectly :)
editChild = (id, first, last, prof) => {
var updatedChild = {
firstName: first,
lastName: last,
profile: prof
}
this.setState(prevState => {
const children = [...prevState.children]
const childIndex = children.findIndex(child => child.id === id)
children[childIndex] = { ...children[childIndex], ...updatedChild }
return { children }
})
console.log(this.state)
}
javascript reactjs
I am trying to update purely just the firstName, lastName and profile for an object without destroying any other data within that object...
Here's an example of the current state.
state = {
children: [
{
id: 1,
firstName: 'Bella',
lastName: 'Laupama',
profile: 'child_care',
schedules: [
{
id: 1,
date: '25 December, 2018',
parent: 'Chris',
activity: 'Christmas'
},
{
id: 2,
date: '28 December, 2018',
parent: 'Mischa',
activity: 'Christmas with Malane Whanau'
},
{
id: 3,
date: '31 December, 2018',
parent: 'Laura',
activity: 'New Years Eve'
},
{
id: 4,
date: '1 January, 2019',
parent: 'Laura',
activity: 'New Years Day'
}
]
}
]
}
And here's the current function I'm trying to pass it to update the current state...
editChild = (first, last, prof) => {
var updatedChild = {
firstName: first,
lastName: last,
profile: prof
}
var children = this.state.children
for (var i = 0; i < children.length; i++) {
if (children[i].firstName === first) {
children[i] = updatedChild
}
}
this.setState({ children })
}
**UPDATE**
Here's the code where I'm calling the function ( from a child component )
export default class EditChild extends React.Component {
state = {
firstName: '',
lastName: '',
profile: '',
}
handleChange = e => {
this.setState({
[e.target.name]: e.target.value
})
}
submitHandler = e => {
e.preventDefault()
this.props.editChild(this.state.firstName, this.state.lastName, this.state.profile)
// Final validation before submitting to server
console.log('SUBMITTED:', this.state)
// Clear the state to clear the form
this.setState({
firstName: '',
lastName: '',
profile: ''
})
}
...form etc is in the render etc...
The form works fine and console logs the result like this:
SUBMITTED:
{firstName: "Donald", lastName: "Trump", profile: "face"}
UPDATE
Thank you to @Tholle and @charlietfl for leading me in the right direction. Basically I needed to be passing the ID as well, and not trying to match based off the first name, as the first name is obviously something that can be changed from the edit form as well. So if I changed Bella Laupama to Charlie Chaplan, it wouldn't find the id.
So I used @Tholle code and modified it to search and replace by id and it worked perfectly :)
editChild = (id, first, last, prof) => {
var updatedChild = {
firstName: first,
lastName: last,
profile: prof
}
this.setState(prevState => {
const children = [...prevState.children]
const childIndex = children.findIndex(child => child.id === id)
children[childIndex] = { ...children[childIndex], ...updatedChild }
return { children }
})
console.log(this.state)
}
javascript reactjs
javascript reactjs
edited Nov 21 '18 at 23:42
Tearz
asked Nov 21 '18 at 23:08
TearzTearz
384
384
Just matching first names seems very flaky since in general first names aren't unique. Don't you have a reference to the original object at the time you are editing it? Show how you useeditChild()
– charlietfl
Nov 21 '18 at 23:13
if you do a console.log afterif (children[i].firstName === first)
, do you get something when you would expect it? Also I don't think this is what you want... this would remove theschedules
andid
properties.
– Katie.Sun
Nov 21 '18 at 23:13
@charlietfl I just updated the post to show the editChild() in action.
– Tearz
Nov 21 '18 at 23:31
add a comment |
Just matching first names seems very flaky since in general first names aren't unique. Don't you have a reference to the original object at the time you are editing it? Show how you useeditChild()
– charlietfl
Nov 21 '18 at 23:13
if you do a console.log afterif (children[i].firstName === first)
, do you get something when you would expect it? Also I don't think this is what you want... this would remove theschedules
andid
properties.
– Katie.Sun
Nov 21 '18 at 23:13
@charlietfl I just updated the post to show the editChild() in action.
– Tearz
Nov 21 '18 at 23:31
Just matching first names seems very flaky since in general first names aren't unique. Don't you have a reference to the original object at the time you are editing it? Show how you use
editChild()
– charlietfl
Nov 21 '18 at 23:13
Just matching first names seems very flaky since in general first names aren't unique. Don't you have a reference to the original object at the time you are editing it? Show how you use
editChild()
– charlietfl
Nov 21 '18 at 23:13
if you do a console.log after
if (children[i].firstName === first)
, do you get something when you would expect it? Also I don't think this is what you want... this would remove the schedules
and id
properties.– Katie.Sun
Nov 21 '18 at 23:13
if you do a console.log after
if (children[i].firstName === first)
, do you get something when you would expect it? Also I don't think this is what you want... this would remove the schedules
and id
properties.– Katie.Sun
Nov 21 '18 at 23:13
@charlietfl I just updated the post to show the editChild() in action.
– Tearz
Nov 21 '18 at 23:31
@charlietfl I just updated the post to show the editChild() in action.
– Tearz
Nov 21 '18 at 23:31
add a comment |
2 Answers
2
active
oldest
votes
You can get the index of the child with findIndex
and then replace the object with that index in a new array with a copy of the original object with all the properties in updatedChild
added to it.
Example
class App extends React.Component {
state = {
children: [
{
id: 1,
firstName: "Bella",
lastName: "Laupama",
profile: "child_care",
schedules: [
{
id: 1,
date: "25 December, 2018",
parent: "Chris",
activity: "Christmas"
},
{
id: 2,
date: "28 December, 2018",
parent: "Mischa",
activity: "Christmas with Malane Whanau"
},
{
id: 3,
date: "31 December, 2018",
parent: "Laura",
activity: "New Years Eve"
},
{
id: 4,
date: "1 January, 2019",
parent: "Laura",
activity: "New Years Day"
}
]
}
]
};
editChild = (first, last, prof) => {
var updatedChild = {
firstName: first,
lastName: last,
profile: prof
};
this.setState(prevState => {
const children = [...prevState.children];
const childIndex = children.findIndex(child => child.firstName === first);
children[childIndex] = { ...children[childIndex], ...updatedChild };
return { children };
});
};
render() {
return (
<div>
<div>{JSON.stringify(this.state)}</div>
<button onClick={() => this.editChild("Bella", "Doe", "Programmer")}>
Edit child
</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
add a comment |
You can do what you're looking for using ES6 Object spread syntax:
import React from "react";
import ReactDOM from "react-dom";
class App extends React.Component {
state = {
firstName: "Bill",
lastName: "Gates",
age: 2018
};
update = (firstName, lastName) => {
const newObj = { firstName, lastName };
this.setState({ ...newObj });
};
render() {
return (
<h1>
<button onClick={() => this.update("Steve", "Jobs")}>
Click to update
</button>
<hr />
{this.state.firstName} {this.state.lastName} {this.state.age}
</h1>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
CodeSandbox example here.
What's happening here with this.setState({ ... newObj })
is that any values in this.state.
which have the keys which match the keys in newObj
will be overwritten with the values from newObj
, and leave the other values unchanged.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53421713%2fhow-to-edit-update-an-object-in-an-array-and-keep-all-other-nested-data%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can get the index of the child with findIndex
and then replace the object with that index in a new array with a copy of the original object with all the properties in updatedChild
added to it.
Example
class App extends React.Component {
state = {
children: [
{
id: 1,
firstName: "Bella",
lastName: "Laupama",
profile: "child_care",
schedules: [
{
id: 1,
date: "25 December, 2018",
parent: "Chris",
activity: "Christmas"
},
{
id: 2,
date: "28 December, 2018",
parent: "Mischa",
activity: "Christmas with Malane Whanau"
},
{
id: 3,
date: "31 December, 2018",
parent: "Laura",
activity: "New Years Eve"
},
{
id: 4,
date: "1 January, 2019",
parent: "Laura",
activity: "New Years Day"
}
]
}
]
};
editChild = (first, last, prof) => {
var updatedChild = {
firstName: first,
lastName: last,
profile: prof
};
this.setState(prevState => {
const children = [...prevState.children];
const childIndex = children.findIndex(child => child.firstName === first);
children[childIndex] = { ...children[childIndex], ...updatedChild };
return { children };
});
};
render() {
return (
<div>
<div>{JSON.stringify(this.state)}</div>
<button onClick={() => this.editChild("Bella", "Doe", "Programmer")}>
Edit child
</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
add a comment |
You can get the index of the child with findIndex
and then replace the object with that index in a new array with a copy of the original object with all the properties in updatedChild
added to it.
Example
class App extends React.Component {
state = {
children: [
{
id: 1,
firstName: "Bella",
lastName: "Laupama",
profile: "child_care",
schedules: [
{
id: 1,
date: "25 December, 2018",
parent: "Chris",
activity: "Christmas"
},
{
id: 2,
date: "28 December, 2018",
parent: "Mischa",
activity: "Christmas with Malane Whanau"
},
{
id: 3,
date: "31 December, 2018",
parent: "Laura",
activity: "New Years Eve"
},
{
id: 4,
date: "1 January, 2019",
parent: "Laura",
activity: "New Years Day"
}
]
}
]
};
editChild = (first, last, prof) => {
var updatedChild = {
firstName: first,
lastName: last,
profile: prof
};
this.setState(prevState => {
const children = [...prevState.children];
const childIndex = children.findIndex(child => child.firstName === first);
children[childIndex] = { ...children[childIndex], ...updatedChild };
return { children };
});
};
render() {
return (
<div>
<div>{JSON.stringify(this.state)}</div>
<button onClick={() => this.editChild("Bella", "Doe", "Programmer")}>
Edit child
</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
add a comment |
You can get the index of the child with findIndex
and then replace the object with that index in a new array with a copy of the original object with all the properties in updatedChild
added to it.
Example
class App extends React.Component {
state = {
children: [
{
id: 1,
firstName: "Bella",
lastName: "Laupama",
profile: "child_care",
schedules: [
{
id: 1,
date: "25 December, 2018",
parent: "Chris",
activity: "Christmas"
},
{
id: 2,
date: "28 December, 2018",
parent: "Mischa",
activity: "Christmas with Malane Whanau"
},
{
id: 3,
date: "31 December, 2018",
parent: "Laura",
activity: "New Years Eve"
},
{
id: 4,
date: "1 January, 2019",
parent: "Laura",
activity: "New Years Day"
}
]
}
]
};
editChild = (first, last, prof) => {
var updatedChild = {
firstName: first,
lastName: last,
profile: prof
};
this.setState(prevState => {
const children = [...prevState.children];
const childIndex = children.findIndex(child => child.firstName === first);
children[childIndex] = { ...children[childIndex], ...updatedChild };
return { children };
});
};
render() {
return (
<div>
<div>{JSON.stringify(this.state)}</div>
<button onClick={() => this.editChild("Bella", "Doe", "Programmer")}>
Edit child
</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
You can get the index of the child with findIndex
and then replace the object with that index in a new array with a copy of the original object with all the properties in updatedChild
added to it.
Example
class App extends React.Component {
state = {
children: [
{
id: 1,
firstName: "Bella",
lastName: "Laupama",
profile: "child_care",
schedules: [
{
id: 1,
date: "25 December, 2018",
parent: "Chris",
activity: "Christmas"
},
{
id: 2,
date: "28 December, 2018",
parent: "Mischa",
activity: "Christmas with Malane Whanau"
},
{
id: 3,
date: "31 December, 2018",
parent: "Laura",
activity: "New Years Eve"
},
{
id: 4,
date: "1 January, 2019",
parent: "Laura",
activity: "New Years Day"
}
]
}
]
};
editChild = (first, last, prof) => {
var updatedChild = {
firstName: first,
lastName: last,
profile: prof
};
this.setState(prevState => {
const children = [...prevState.children];
const childIndex = children.findIndex(child => child.firstName === first);
children[childIndex] = { ...children[childIndex], ...updatedChild };
return { children };
});
};
render() {
return (
<div>
<div>{JSON.stringify(this.state)}</div>
<button onClick={() => this.editChild("Bella", "Doe", "Programmer")}>
Edit child
</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
class App extends React.Component {
state = {
children: [
{
id: 1,
firstName: "Bella",
lastName: "Laupama",
profile: "child_care",
schedules: [
{
id: 1,
date: "25 December, 2018",
parent: "Chris",
activity: "Christmas"
},
{
id: 2,
date: "28 December, 2018",
parent: "Mischa",
activity: "Christmas with Malane Whanau"
},
{
id: 3,
date: "31 December, 2018",
parent: "Laura",
activity: "New Years Eve"
},
{
id: 4,
date: "1 January, 2019",
parent: "Laura",
activity: "New Years Day"
}
]
}
]
};
editChild = (first, last, prof) => {
var updatedChild = {
firstName: first,
lastName: last,
profile: prof
};
this.setState(prevState => {
const children = [...prevState.children];
const childIndex = children.findIndex(child => child.firstName === first);
children[childIndex] = { ...children[childIndex], ...updatedChild };
return { children };
});
};
render() {
return (
<div>
<div>{JSON.stringify(this.state)}</div>
<button onClick={() => this.editChild("Bella", "Doe", "Programmer")}>
Edit child
</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
class App extends React.Component {
state = {
children: [
{
id: 1,
firstName: "Bella",
lastName: "Laupama",
profile: "child_care",
schedules: [
{
id: 1,
date: "25 December, 2018",
parent: "Chris",
activity: "Christmas"
},
{
id: 2,
date: "28 December, 2018",
parent: "Mischa",
activity: "Christmas with Malane Whanau"
},
{
id: 3,
date: "31 December, 2018",
parent: "Laura",
activity: "New Years Eve"
},
{
id: 4,
date: "1 January, 2019",
parent: "Laura",
activity: "New Years Day"
}
]
}
]
};
editChild = (first, last, prof) => {
var updatedChild = {
firstName: first,
lastName: last,
profile: prof
};
this.setState(prevState => {
const children = [...prevState.children];
const childIndex = children.findIndex(child => child.firstName === first);
children[childIndex] = { ...children[childIndex], ...updatedChild };
return { children };
});
};
render() {
return (
<div>
<div>{JSON.stringify(this.state)}</div>
<button onClick={() => this.editChild("Bella", "Doe", "Programmer")}>
Edit child
</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
answered Nov 21 '18 at 23:21
TholleTholle
40.3k54567
40.3k54567
add a comment |
add a comment |
You can do what you're looking for using ES6 Object spread syntax:
import React from "react";
import ReactDOM from "react-dom";
class App extends React.Component {
state = {
firstName: "Bill",
lastName: "Gates",
age: 2018
};
update = (firstName, lastName) => {
const newObj = { firstName, lastName };
this.setState({ ...newObj });
};
render() {
return (
<h1>
<button onClick={() => this.update("Steve", "Jobs")}>
Click to update
</button>
<hr />
{this.state.firstName} {this.state.lastName} {this.state.age}
</h1>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
CodeSandbox example here.
What's happening here with this.setState({ ... newObj })
is that any values in this.state.
which have the keys which match the keys in newObj
will be overwritten with the values from newObj
, and leave the other values unchanged.
add a comment |
You can do what you're looking for using ES6 Object spread syntax:
import React from "react";
import ReactDOM from "react-dom";
class App extends React.Component {
state = {
firstName: "Bill",
lastName: "Gates",
age: 2018
};
update = (firstName, lastName) => {
const newObj = { firstName, lastName };
this.setState({ ...newObj });
};
render() {
return (
<h1>
<button onClick={() => this.update("Steve", "Jobs")}>
Click to update
</button>
<hr />
{this.state.firstName} {this.state.lastName} {this.state.age}
</h1>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
CodeSandbox example here.
What's happening here with this.setState({ ... newObj })
is that any values in this.state.
which have the keys which match the keys in newObj
will be overwritten with the values from newObj
, and leave the other values unchanged.
add a comment |
You can do what you're looking for using ES6 Object spread syntax:
import React from "react";
import ReactDOM from "react-dom";
class App extends React.Component {
state = {
firstName: "Bill",
lastName: "Gates",
age: 2018
};
update = (firstName, lastName) => {
const newObj = { firstName, lastName };
this.setState({ ...newObj });
};
render() {
return (
<h1>
<button onClick={() => this.update("Steve", "Jobs")}>
Click to update
</button>
<hr />
{this.state.firstName} {this.state.lastName} {this.state.age}
</h1>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
CodeSandbox example here.
What's happening here with this.setState({ ... newObj })
is that any values in this.state.
which have the keys which match the keys in newObj
will be overwritten with the values from newObj
, and leave the other values unchanged.
You can do what you're looking for using ES6 Object spread syntax:
import React from "react";
import ReactDOM from "react-dom";
class App extends React.Component {
state = {
firstName: "Bill",
lastName: "Gates",
age: 2018
};
update = (firstName, lastName) => {
const newObj = { firstName, lastName };
this.setState({ ...newObj });
};
render() {
return (
<h1>
<button onClick={() => this.update("Steve", "Jobs")}>
Click to update
</button>
<hr />
{this.state.firstName} {this.state.lastName} {this.state.age}
</h1>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
CodeSandbox example here.
What's happening here with this.setState({ ... newObj })
is that any values in this.state.
which have the keys which match the keys in newObj
will be overwritten with the values from newObj
, and leave the other values unchanged.
answered Nov 21 '18 at 23:22
ColinColin
4,5352830
4,5352830
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53421713%2fhow-to-edit-update-an-object-in-an-array-and-keep-all-other-nested-data%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Just matching first names seems very flaky since in general first names aren't unique. Don't you have a reference to the original object at the time you are editing it? Show how you use
editChild()
– charlietfl
Nov 21 '18 at 23:13
if you do a console.log after
if (children[i].firstName === first)
, do you get something when you would expect it? Also I don't think this is what you want... this would remove theschedules
andid
properties.– Katie.Sun
Nov 21 '18 at 23:13
@charlietfl I just updated the post to show the editChild() in action.
– Tearz
Nov 21 '18 at 23:31