JavaScript | Spread operator update nested value












1















I am trying to update a nested value of an object using the spread operator. This is my first time using this and I believe I am pretty close to achieving my end goal but I just can't seem to figure out what I actually need to do next.



I have an array which is structured like this:



[
{
name: "Category 1",
posts: [
{
id: 1,
published: false,
category: "Category 1"
},
{
id: 2,
published: true,
category: "Category 1"
}
]
},
{
name: "Category 2",
posts: [
{
id: 3,
published: true,
category: "Category 2"
},
{
id: 4,
published: true,
category: "Category 2"
}
]
}
]


On the click of a button I am trying to update the published value, and as I am using React I need to set the state. So it got recommended to me that I update using the spread operator.



onPostClick(post) {
post.pubished = !post.published;
this.setState({...this.state.posts[post.category], post})
}


If I log out the result of {...this.state.posts[post.category], post} I can see that the published is getting added to the parent which forms:



{
name: "Category 1",
published: false,
posts: [
...
]
}


Obviously this isn't the intended result, I want it to update the actual object within the posts object.



I have tried to do something like this.setState({...this.state.posts[post.category].posts, post}) but I get a message that it is undefined.










share|improve this question

























  • onPostClick(post) - what is post format, does it contain full data together with id / category etc. ?

    – Goran.it
    Nov 24 '18 at 10:47











  • The format is { id: 1, category: 'Category 1', published: true }

    – connormiotk96
    Nov 24 '18 at 10:52











  • So yes @Goran.it it contains all of the data

    – connormiotk96
    Nov 24 '18 at 10:52
















1















I am trying to update a nested value of an object using the spread operator. This is my first time using this and I believe I am pretty close to achieving my end goal but I just can't seem to figure out what I actually need to do next.



I have an array which is structured like this:



[
{
name: "Category 1",
posts: [
{
id: 1,
published: false,
category: "Category 1"
},
{
id: 2,
published: true,
category: "Category 1"
}
]
},
{
name: "Category 2",
posts: [
{
id: 3,
published: true,
category: "Category 2"
},
{
id: 4,
published: true,
category: "Category 2"
}
]
}
]


On the click of a button I am trying to update the published value, and as I am using React I need to set the state. So it got recommended to me that I update using the spread operator.



onPostClick(post) {
post.pubished = !post.published;
this.setState({...this.state.posts[post.category], post})
}


If I log out the result of {...this.state.posts[post.category], post} I can see that the published is getting added to the parent which forms:



{
name: "Category 1",
published: false,
posts: [
...
]
}


Obviously this isn't the intended result, I want it to update the actual object within the posts object.



I have tried to do something like this.setState({...this.state.posts[post.category].posts, post}) but I get a message that it is undefined.










share|improve this question

























  • onPostClick(post) - what is post format, does it contain full data together with id / category etc. ?

    – Goran.it
    Nov 24 '18 at 10:47











  • The format is { id: 1, category: 'Category 1', published: true }

    – connormiotk96
    Nov 24 '18 at 10:52











  • So yes @Goran.it it contains all of the data

    – connormiotk96
    Nov 24 '18 at 10:52














1












1








1








I am trying to update a nested value of an object using the spread operator. This is my first time using this and I believe I am pretty close to achieving my end goal but I just can't seem to figure out what I actually need to do next.



I have an array which is structured like this:



[
{
name: "Category 1",
posts: [
{
id: 1,
published: false,
category: "Category 1"
},
{
id: 2,
published: true,
category: "Category 1"
}
]
},
{
name: "Category 2",
posts: [
{
id: 3,
published: true,
category: "Category 2"
},
{
id: 4,
published: true,
category: "Category 2"
}
]
}
]


On the click of a button I am trying to update the published value, and as I am using React I need to set the state. So it got recommended to me that I update using the spread operator.



onPostClick(post) {
post.pubished = !post.published;
this.setState({...this.state.posts[post.category], post})
}


If I log out the result of {...this.state.posts[post.category], post} I can see that the published is getting added to the parent which forms:



{
name: "Category 1",
published: false,
posts: [
...
]
}


Obviously this isn't the intended result, I want it to update the actual object within the posts object.



I have tried to do something like this.setState({...this.state.posts[post.category].posts, post}) but I get a message that it is undefined.










share|improve this question
















I am trying to update a nested value of an object using the spread operator. This is my first time using this and I believe I am pretty close to achieving my end goal but I just can't seem to figure out what I actually need to do next.



I have an array which is structured like this:



[
{
name: "Category 1",
posts: [
{
id: 1,
published: false,
category: "Category 1"
},
{
id: 2,
published: true,
category: "Category 1"
}
]
},
{
name: "Category 2",
posts: [
{
id: 3,
published: true,
category: "Category 2"
},
{
id: 4,
published: true,
category: "Category 2"
}
]
}
]


On the click of a button I am trying to update the published value, and as I am using React I need to set the state. So it got recommended to me that I update using the spread operator.



onPostClick(post) {
post.pubished = !post.published;
this.setState({...this.state.posts[post.category], post})
}


If I log out the result of {...this.state.posts[post.category], post} I can see that the published is getting added to the parent which forms:



{
name: "Category 1",
published: false,
posts: [
...
]
}


Obviously this isn't the intended result, I want it to update the actual object within the posts object.



I have tried to do something like this.setState({...this.state.posts[post.category].posts, post}) but I get a message that it is undefined.







javascript reactjs ecmascript-6 spread-syntax






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 27 at 3:21









dwjohnston

2,834114891




2,834114891










asked Nov 24 '18 at 10:37









connormiotk96connormiotk96

277




277













  • onPostClick(post) - what is post format, does it contain full data together with id / category etc. ?

    – Goran.it
    Nov 24 '18 at 10:47











  • The format is { id: 1, category: 'Category 1', published: true }

    – connormiotk96
    Nov 24 '18 at 10:52











  • So yes @Goran.it it contains all of the data

    – connormiotk96
    Nov 24 '18 at 10:52



















  • onPostClick(post) - what is post format, does it contain full data together with id / category etc. ?

    – Goran.it
    Nov 24 '18 at 10:47











  • The format is { id: 1, category: 'Category 1', published: true }

    – connormiotk96
    Nov 24 '18 at 10:52











  • So yes @Goran.it it contains all of the data

    – connormiotk96
    Nov 24 '18 at 10:52

















onPostClick(post) - what is post format, does it contain full data together with id / category etc. ?

– Goran.it
Nov 24 '18 at 10:47





onPostClick(post) - what is post format, does it contain full data together with id / category etc. ?

– Goran.it
Nov 24 '18 at 10:47













The format is { id: 1, category: 'Category 1', published: true }

– connormiotk96
Nov 24 '18 at 10:52





The format is { id: 1, category: 'Category 1', published: true }

– connormiotk96
Nov 24 '18 at 10:52













So yes @Goran.it it contains all of the data

– connormiotk96
Nov 24 '18 at 10:52





So yes @Goran.it it contains all of the data

– connormiotk96
Nov 24 '18 at 10:52












2 Answers
2






active

oldest

votes


















1














You can't access your data with this.state.posts[post.category]. posts data in the objects of the array.



You can make a filter to find your category object in array and change its posts value.



onPostClick(post) {
//CLONE YOUR DATA
var postArray = this.state.posts;

//FIND YOUR CATEGORY OBJECT IN ARRAY
var categoryIndex = postArray.findIndex(function(obj){
return obj.name === post.category;
});

//FIND YOUR POST AND CHANGE PUBLISHED VALUE
postArray[categoryIndex].posts.forEach(function(item){
if (item.id === post.id) {
item.published = !item.published;
}
});
//SET TO STATE TO RERENDER
this.setState({ posts: postArray});
}


This should work if your name of the state is true.






share|improve this answer


























  • Thanks for the answer! Before I try this, I just wanted to ask. How come you opted for a for () loop rather than .forEach ? Is there a reason for this or is it personal preference?

    – connormiotk96
    Nov 24 '18 at 11:17











  • @connormiotk96 that came to my mind first. Updated with forEach.

    – akcoban
    Nov 24 '18 at 11:32



















0














just adding, we know there are many ways to succeed, maybe you also want to try this way too..



onPostClick = post => {
let published = this.state.data.map((item, i) => {
item.posts.map((item_post, i) => {
if (item_post.category === post.category) {
item_post.published = !post.published;
}
});
});
this.setState({ ...this.state.data, published });
};





share|improve this answer

























    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
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53457283%2fjavascript-spread-operator-update-nested-value%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









    1














    You can't access your data with this.state.posts[post.category]. posts data in the objects of the array.



    You can make a filter to find your category object in array and change its posts value.



    onPostClick(post) {
    //CLONE YOUR DATA
    var postArray = this.state.posts;

    //FIND YOUR CATEGORY OBJECT IN ARRAY
    var categoryIndex = postArray.findIndex(function(obj){
    return obj.name === post.category;
    });

    //FIND YOUR POST AND CHANGE PUBLISHED VALUE
    postArray[categoryIndex].posts.forEach(function(item){
    if (item.id === post.id) {
    item.published = !item.published;
    }
    });
    //SET TO STATE TO RERENDER
    this.setState({ posts: postArray});
    }


    This should work if your name of the state is true.






    share|improve this answer


























    • Thanks for the answer! Before I try this, I just wanted to ask. How come you opted for a for () loop rather than .forEach ? Is there a reason for this or is it personal preference?

      – connormiotk96
      Nov 24 '18 at 11:17











    • @connormiotk96 that came to my mind first. Updated with forEach.

      – akcoban
      Nov 24 '18 at 11:32
















    1














    You can't access your data with this.state.posts[post.category]. posts data in the objects of the array.



    You can make a filter to find your category object in array and change its posts value.



    onPostClick(post) {
    //CLONE YOUR DATA
    var postArray = this.state.posts;

    //FIND YOUR CATEGORY OBJECT IN ARRAY
    var categoryIndex = postArray.findIndex(function(obj){
    return obj.name === post.category;
    });

    //FIND YOUR POST AND CHANGE PUBLISHED VALUE
    postArray[categoryIndex].posts.forEach(function(item){
    if (item.id === post.id) {
    item.published = !item.published;
    }
    });
    //SET TO STATE TO RERENDER
    this.setState({ posts: postArray});
    }


    This should work if your name of the state is true.






    share|improve this answer


























    • Thanks for the answer! Before I try this, I just wanted to ask. How come you opted for a for () loop rather than .forEach ? Is there a reason for this or is it personal preference?

      – connormiotk96
      Nov 24 '18 at 11:17











    • @connormiotk96 that came to my mind first. Updated with forEach.

      – akcoban
      Nov 24 '18 at 11:32














    1












    1








    1







    You can't access your data with this.state.posts[post.category]. posts data in the objects of the array.



    You can make a filter to find your category object in array and change its posts value.



    onPostClick(post) {
    //CLONE YOUR DATA
    var postArray = this.state.posts;

    //FIND YOUR CATEGORY OBJECT IN ARRAY
    var categoryIndex = postArray.findIndex(function(obj){
    return obj.name === post.category;
    });

    //FIND YOUR POST AND CHANGE PUBLISHED VALUE
    postArray[categoryIndex].posts.forEach(function(item){
    if (item.id === post.id) {
    item.published = !item.published;
    }
    });
    //SET TO STATE TO RERENDER
    this.setState({ posts: postArray});
    }


    This should work if your name of the state is true.






    share|improve this answer















    You can't access your data with this.state.posts[post.category]. posts data in the objects of the array.



    You can make a filter to find your category object in array and change its posts value.



    onPostClick(post) {
    //CLONE YOUR DATA
    var postArray = this.state.posts;

    //FIND YOUR CATEGORY OBJECT IN ARRAY
    var categoryIndex = postArray.findIndex(function(obj){
    return obj.name === post.category;
    });

    //FIND YOUR POST AND CHANGE PUBLISHED VALUE
    postArray[categoryIndex].posts.forEach(function(item){
    if (item.id === post.id) {
    item.published = !item.published;
    }
    });
    //SET TO STATE TO RERENDER
    this.setState({ posts: postArray});
    }


    This should work if your name of the state is true.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 24 '18 at 11:25

























    answered Nov 24 '18 at 11:10









    akcobanakcoban

    42119




    42119













    • Thanks for the answer! Before I try this, I just wanted to ask. How come you opted for a for () loop rather than .forEach ? Is there a reason for this or is it personal preference?

      – connormiotk96
      Nov 24 '18 at 11:17











    • @connormiotk96 that came to my mind first. Updated with forEach.

      – akcoban
      Nov 24 '18 at 11:32



















    • Thanks for the answer! Before I try this, I just wanted to ask. How come you opted for a for () loop rather than .forEach ? Is there a reason for this or is it personal preference?

      – connormiotk96
      Nov 24 '18 at 11:17











    • @connormiotk96 that came to my mind first. Updated with forEach.

      – akcoban
      Nov 24 '18 at 11:32

















    Thanks for the answer! Before I try this, I just wanted to ask. How come you opted for a for () loop rather than .forEach ? Is there a reason for this or is it personal preference?

    – connormiotk96
    Nov 24 '18 at 11:17





    Thanks for the answer! Before I try this, I just wanted to ask. How come you opted for a for () loop rather than .forEach ? Is there a reason for this or is it personal preference?

    – connormiotk96
    Nov 24 '18 at 11:17













    @connormiotk96 that came to my mind first. Updated with forEach.

    – akcoban
    Nov 24 '18 at 11:32





    @connormiotk96 that came to my mind first. Updated with forEach.

    – akcoban
    Nov 24 '18 at 11:32













    0














    just adding, we know there are many ways to succeed, maybe you also want to try this way too..



    onPostClick = post => {
    let published = this.state.data.map((item, i) => {
    item.posts.map((item_post, i) => {
    if (item_post.category === post.category) {
    item_post.published = !post.published;
    }
    });
    });
    this.setState({ ...this.state.data, published });
    };





    share|improve this answer






























      0














      just adding, we know there are many ways to succeed, maybe you also want to try this way too..



      onPostClick = post => {
      let published = this.state.data.map((item, i) => {
      item.posts.map((item_post, i) => {
      if (item_post.category === post.category) {
      item_post.published = !post.published;
      }
      });
      });
      this.setState({ ...this.state.data, published });
      };





      share|improve this answer




























        0












        0








        0







        just adding, we know there are many ways to succeed, maybe you also want to try this way too..



        onPostClick = post => {
        let published = this.state.data.map((item, i) => {
        item.posts.map((item_post, i) => {
        if (item_post.category === post.category) {
        item_post.published = !post.published;
        }
        });
        });
        this.setState({ ...this.state.data, published });
        };





        share|improve this answer















        just adding, we know there are many ways to succeed, maybe you also want to try this way too..



        onPostClick = post => {
        let published = this.state.data.map((item, i) => {
        item.posts.map((item_post, i) => {
        if (item_post.category === post.category) {
        item_post.published = !post.published;
        }
        });
        });
        this.setState({ ...this.state.data, published });
        };






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 24 '18 at 12:07

























        answered Nov 24 '18 at 11:53









        sgtkuncorosgtkuncoro

        1556




        1556






























            draft saved

            draft discarded




















































            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.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53457283%2fjavascript-spread-operator-update-nested-value%23new-answer', 'question_page');
            }
            );

            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







            Popular posts from this blog

            Ottavio Pratesi

            Tricia Helfer

            15 giugno