1

so i have some cases.

Add category to every object in array, which holds in state

Posts, are array of object ( these object are wordpress article, and have a lot of parameters)

It's holded in state:

constructor(props) {
    super(props);
    this.state = {
      posts: [],
      postCategories: [],
    };
  }

Later i getting data from other endpoints (category for every posts, from another endpoint)

      fetch(postsUrl)
        .then(data => data.json())
        .then(data => {
            this.setState({
               posts: data,
            })
            const postcategory = data.map((category) => category.categories)

            if (postcategory === 2)
            {
                console.log("category1" + postcategory)
            }
            if(postcategory === 3){
                console.log("category2" + postcategory)
            }
        })

postcategory - every category from every posts (But it's enum not string (1,2,3 etc.))

I need to add parameter to every object in array - posts depends on e.num (if posts[0] have postcategory 1 i need to inject parameter name: category, with content dependend on enum.

eg. for post[0] it's postcategory = 2 so i need to inject parameter name: category with value "category2"

Additionally, the solution should include all objects in the array - loop?

2 Answers 2

2

You can use map and spread to achieve this

const result = array.map(item =>{
    if(condition1)
        return {...item, newProperty: 'foo'}

    if(condition2)
       return {...item, anotherProp: 'bar'}

    return item
})
Sign up to request clarification or add additional context in comments.

8 Comments

Wow thanks, it's adding parameter to every object, now i going to try match this to my problem :)
Ok, i implement it to my solution and it's generally work, now i trying resolve the issue with conditions
If you want post another question!
if(item.categories === 2), if(item.categories === 3) These condition didn't add parameter name to every object of array
Could you post another question explaining better? Comments are just messy!
|
1

To alter the data received from the fetch, you have to change the data inside the map function. The whole array will be returned into newPostData which you can then set in state.

fetch(postsUrl)
.then(data => data.json())
.then(data => {
  const newPostData = data.map(item => {
    if (item.categories === 2) {
      item.myNewValue = 'the new value if categories is 2';
    }
    if (item.categories === 3)
      console.log('Categories equals 3')

    return item
  }

  this.setState({posts: newPostData})
})

1 Comment

You're mutating the state

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.