Javascript Creating Array In Object And Push Data To The Array
I'm new to programming. I'm trying React and have function addComment which is executed when a user adds a comment to news.I need to create in this moment a property comments (arra
Solution 1:
Let's say you have an object like this.
foo : {
bar : "x"
}
To create an array, simply initialize it to an empty array.
foo.newArray = []
If you console.log(foo)
, you will now see this
foo : {
bar : "x",
newArray : []
}
This means your foo
object has an empty array called newArray
. You can add elements to it using the push()
method.
Push a variable like this foo.newArray.push(myVariable);
Push a string like this foo.newArray.push("myString");
Push an object like this
foo.newArray.push({
"bar2" : "val2"
});
For more information on arrays check W3schools
In your particular case, just do ARTICLES.push({})
Solution 2:
assuming that data exist in component's state , then handler will look something like that
addComment(index, inputCommentValue){
// copy array , for not mutate stateletARTICLES = [...this.state.ARTICLES];
// check if comments not existif(!ARTICLES[index].comments) ARTICLES[index].comments=[];
// add new comment to arrayARTICLES[index].comments.push(inputCommentValue);
// update component with new articlesthis.setState({ARTICLES:ARTICLES});
}
Post a Comment for "Javascript Creating Array In Object And Push Data To The Array"