javascript - 如何在单击时创建数组数组并通过数据属性检查数组是否存在于数组中并推送到该数组
问题描述
我正在尝试为我正在构建的过滤器创建一个数组数组。我需要得到这样的结果:
terms = {
'writer_category' = {
'1','2','3','4';
},
'status' = {
'1','2','3','4';
}
}
到目前为止,我已经将对象推送到主数组,但我不知道如何通过键(writer_category)检查数组并将 ID(数字)添加到其中。它只是不断创建新对象。
这是一个点击功能,它获取 2 个数据属性(一个术语类型和一个术语 ID),我需要获取该信息并执行以下操作:
如果类型存在 - 向该对象添加 id 否则创建对象并添加 id
如果你能给我任何非常感激的指点
解决方案
根据你的描述
如果类型存在 - 将 id 添加到该对象,否则创建对象并添加 id
const terms = {};
function addValues(type, id){
if (!!~Object.keys(terms).indexOf(type)) {
terms[type].push(id) // If type exist push the id
} else {
terms[type] = [id]; // If type doesn't exist create it, and assign an array
}
}
推荐阅读
- java - 如何在 JDesktopPane 的背景中创建 JLabel?
- python - Rosrun 命令不执行 python 文件
- php - 图片上传不会在文件夹中创建图片,只在数据库中
- regex - 如何使用正则表达式
- javascript - 如何在 react-native 中获取 TextInput 值
- playframework - 使用 Play Framework for Java,如何从控制器返回 500 响应?
- vba - 运行宏时的复制和粘贴保护
- actionscript-3 - AS3 如何将 adMob 添加到 Adobe Flash/Animate?
- python - 有没有办法在 macOS 的扩展坞中更改 Python Launcher 的名称?
- python - BeautifulSoup解析html列表