javascript - 如果值相等,则嵌套数组将对象添加到状态中的数组
问题描述
我正在尝试遍历嵌套的 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"
}]
感谢您的帮助,看不到我在这里缺少什么。
解决方案
您可以通过使用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
变量名将使用计算属性设置,过滤器参数也通过函数参数给出。
推荐阅读
- r - 如何在 R 中使用循环导入 .cvs 文件?
- asp.net - asp.net 和 signalR ,JsonException:检测到可能的对象循环
- linux - C Shell:“如果:表达式语法”
- python - 为什么 dask 的“to_sql”比 pandas 花费更多时间?
- reactjs - Express 服务器无法启动
- android - 如何在 Android Studio 源代码中运行 adb 命令?
- javascript - 阅读 Mongoose 文档时的困惑。Model.prototype vs Document.prototype vs Query.prototype
- javascript - 更多选项按钮无法多次使用
- androidx - TakePicture() 中的 ActivityResultContracts 结果 api 问题
- java - 提取数组组合的算法