0

I am trying to iterate through a nested for loop. If a value if equals to something, I want to add that object to an array in my state.

this.state = {
    custBehavior: [],
    custService: [],
    custEngagement: [],
    custUsage: []
  }

Code

this.props.insights.map((behavior) =>
  behavior.map((items) =>
    {if (items.scoreCategory === "Behavior") {
      this.setState(behaviorInsight => ({
        custBehavior: [...behaviorInsight.custBehavior, items]
      }))
    }}
  )

The prop information is the full JSON below.

If I remove the if statement and do this....

this.props.insights.map((behavior) =>
  behavior.map((items) =>
    console.log(items)
  )
);

I'll get a print out of each object within the array; again, sample JSON is below.

[{
            "scoreModelId": "DNA_APPLE_HML_TAG",
            "scoreDisplayName": "Apple Enthusiast",
            "scoreCategory": "Behavior",
            "scoreSystem": "LMH",
            "scoreValue": "HIGH",
            "scoreDate": "2019-01-05",
            "scoreLevel": "L",
            "scorePriority": 1
        }, {
            "scoreModelId": "DNA_GOOGLE_HML_TAG",
            "scoreDisplayName": "Google Enthusiast",
            "scoreCategory": "Behavior",
            "scoreSystem": "LMH",
            "scoreValue": "HIGH",
            "scoreDate": "2019-01-05",
            "scoreLevel": "L",
            "scorePriority": 1
        }, {
            "scoreModelId": "MG6M_IN_A",
            "scoreDisplayName": "LTV Model",
            "scoreCategory": "Segmentation",
            "scoreSystem": "DECIMAL",
            "scoreValue": "14.06",
            "scoreDecile": "2",
            "scoreCentile": "13",
            "scoreDate": "2019-01-14",
            "scoreLevel": "L"
        }]

I can't see what I am missing here.

8
  • Please don't post sample data as images. Use text format instead. Commented Feb 27, 2019 at 16:44
  • updated with sample data @hindmost Commented Feb 27, 2019 at 16:47
  • I meant all data in your post Commented Feb 27, 2019 at 16:49
  • that is all of the data. Commented Feb 27, 2019 at 16:57
  • Replace all images in the post with text. Commented Feb 27, 2019 at 16:58

2 Answers 2

1

You could achieve it by using reduce. You can then add each items to your final array by filtering every behavior objects.

You should only ever set your state once since it is an asynchronous function

const custBehavior = this.props.insights.reduce(
    (acc, behavior) => [...acc, ...behavior.filter(items => items.scoreCategory === "Behavior")], //Takes out every item corresponding to the filter and adds them to the final array
    [] //The starting value, an empty array
)
this.setState({ custBehavior })

To apply it to other types you could make a function out of the above code :

customCategory = (category, name) => {
    const custThing = this.props.insights.reduce(
        (acc, behavior) => [...acc, ...behavior.filter(items => items.scoreCategory === category)],
        []
    )
    this.setState({ [name]: custThing })
}

//

this.customCategory('Behavior', 'custBehavior')
this.customCategory('Segmentation', 'yourStateVariableName')

The state variable name will be set using computed properties and the filter argument is given via the function parameter too.

Sign up to request clarification or add additional context in comments.

5 Comments

thanks! since I have a few other objects to look for, you can see in my data Segmentation is another, how would this work with other arrays? You can see my state has a total of four arrays ill be using
Well, I guess it depends on what you want to achieve with he other arrays, you could simply change the string in the filter in the best case. Could you post a sample input/output ?
i posted the same json above. in that sample, there was a scorecategory of segmentation. i eventually need to put the data in four specific areas.
so, your code works with the Behavior category, if I wanted to add the other category in there (Segmentation) how would I go about doing that.
I edited my answer, is this what you are trying to do ?
0

Do you need to normalize the data and then change the state

Eg:

const normalizedData = this.props.insights.map((behavior) =>
  behavior.map((items) =>
    if (items.scoreCategory === "Behavior") {
      return ({
        custBehavior: [...behaviorInsight.custBehavior, items]
      })
    }
  ).filter(value => value)

  this.setState({ custBehavior: normalizedData })

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.