如果值相等,则嵌套数组,将对象添加到状态为

时间:2019-02-27 16:41:29

标签: javascript reactjs

我正在尝试遍历嵌套的for循环。如果某个值等于某个值,我想将该对象添加到处于状态的数组中。

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

代码

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

道具信息是下面的完整json。

如果我删除if语句并执行此操作。...

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

再次从数组中的每个对象中获取打印结果,示例json在下面。

样本数据

[{
            "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"
        }]

感谢您的帮助,看不到我在这里缺少的东西。

2 个答案:

答案 0 :(得分:1)

您可以使用reduce来实现。然后,您可以通过过滤每个行为对象将每个items添加到最终数组中。

您应该只设置一次状态,因为它是异步函数

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

要将其应用于其他类型,您可以使用上述代码创建一个函数:

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')

state变量名将使用计算所得的属性进行设置,并且filter参数也是通过function参数给出的。

答案 1 :(得分:0)

是否需要规范化数据然后更改状态

例如:

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