代码之家  ›  专栏  ›  技术社区  ›  nb_nb_nb

从JSON获取唯一值

  •  -3
  • nb_nb_nb  · 技术社区  · 7 年前

    我正在尝试从JSON中获取可以添加到select标记中的唯一值。

    我的JSON:

    [
    {
        "active_subscribers": 11158,
        "date_x": "2018-11-21",
        "segment": "e077"
    },
    {
        "active_subscribers": 11158,
        "date_x": "2018-11-21",
        "segment": "e099"
    },
    {
        "active_subscribers": 11156,
        "date_x": "2018-11-22",
        "segment": "e079
    },
    {
        "active_subscribers": 11156,
        "date_x": "2018-11-22",
        "segment": "e079"
    }
    ]
    

    我想与众不同 segment

    我的预期结果:

    • E077
    • E099
    • E079型
    1 回复  |  直到 7 年前
        1
  •  -1
  •   Atul Sharma    7 年前

    在检查元素是否已经存在于数组中之后,您可以循环遍历每个元素,并继续将它们推送到数组中。

    使用 Array.forEach 循环和 Array.indexOf 检查数组中是否已经存在元素。

    var x = [
    {
        "active_subscribers": 11158,
        "date_x": "2018-11-21",
        "segment": "e077"
    },
    {
        "active_subscribers": 11158,
        "date_x": "2018-11-21",
        "segment": "e099"
    },
    {
        "active_subscribers": 11156,
        "date_x": "2018-11-22",
        "segment": "e079"
    },
    {
        "active_subscribers": 11156,
        "date_x": "2018-11-22",
        "segment": "e079"
    }]
    
    
    var unique = [];
    x.forEach(function(e){
    	if(unique.indexOf(e.segment) == -1){
    		unique.push(e.segment);
    	}
    })
    
    console.log(unique);