如何从数组中获取单个字段

时间:2017-06-23 05:53:56

标签: javascript jquery angularjs arrays

我正在使用如下的数组

var types = [{id:1, type:'Type 2'}, {id:2, type:'Type 5'}, {id:3, type:'Type 1'}, {id:4, type:'Type 2'}];

我想基于Type过滤值并将其转换为单维数组。我尝试使用过滤器等,但获得了过滤后的二维数组。

$filter('filter')(types, { type: 'Type 2' })

结果应该只是没有类型的id数组:

[{id:1}, {id:4}]

5 个答案:

答案 0 :(得分:3)

在过滤数组

后尝试使用Array#map



var types = [{id:1, type:'Type 2'}, {id:2, type:'Type 5'}, {id:3, type:'Type 1'}, {id:4, type:'Type 2'}];

console.log(types.filter(a=> a.type =='Type 2' ).map(a=> ({id : a.id})))




答案 1 :(得分:2)

如果命名约定filter()为真,则不会操纵对象;它选择一个新的子集数组。

您可以使用Array.map()

$filter('filter')(types, { type: 'Type 2' }).map(function(x){
    return { id : x.id };
})

工作小提琴http://jsfiddle.net/ADukg/12074/

答案 2 :(得分:1)

您可以使用index = np.arange(np.shape(csr_matrix)[0]) np.random.shuffle(index) csr_matrix_new = csr_matrix[index, :]filter的组合。或者,您可以使用这个名为map的神奇函数,该函数可以单手reduce以及filter您的数组。像这样:



map




答案 3 :(得分:0)

您好 Vikas Vaidya 您还可以使用以下代码来解决此问题:

function filterArrayofObjects(objKey, objValue) {
    var temp = [], count = -1;
    for (var i in types) {
        var flag = false;
        var obj = {};
        for (var j in types[i]) {
            if (j === objKey && types[i][j] === objValue) {
                flag = true;
                continue;
            }
            obj[j] = types[i][j];
        }
        if (flag) {
            count++;
            temp[count] = obj;
        }
    }
    return temp;
}

var result = filterArrayofObjects("type", "Type 2");
window.console.log(result);

答案 4 :(得分:-1)

您可以使用Underscore js。 _.filter和_.map可以帮助您实现预期的结果

相关问题