首页 > 解决方案 > 如何在单击时创建数组数组并通过数据属性检查数组是否存在于数组中并推送到该数组

问题描述

我正在尝试为我正在构建的过滤器创建一个数组数组。我需要得到这样的结果:

terms = {
    'writer_category' = {
        '1','2','3','4';
    },
    'status' = {
        '1','2','3','4';
    }
}

到目前为止,我已经将对象推送到主数组,但我不知道如何通过键(writer_category)检查数组并将 ID(数字)添加到其中。它只是不断创建新对象。

这是一个点击功能,它获取 2 个数据属性(一个术语类型和一个术语 ID),我需要获取该信息并执行以下操作:

如果类型存在 - 向该对象添加 id 否则创建对象并添加 id

如果你能给我任何非常感激的指点

标签: javascriptarrays

解决方案


根据你的描述

如果类型存在 - 将 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
  }
}


推荐阅读