根据值获取/过滤对象

时间:2016-11-25 15:48:40

标签: javascript arrays object filter

我可以根据值过滤或提取对象的值吗?

例如[10,19]将返回Bill和Sam。

 [ { "id": 10, "nice_name": "Bill" }, 
    { "id": 12, "nice_name": "Dan"}, 
    { "id": 18, "nice_name": "Tony" },
    { "id": 19, "nice_name": "Sam" }, 
]

感谢/

6 个答案:

答案 0 :(得分:3)

您可以链接过滤然后映射函数:

const mySearch = [10, 19]
const result = myArray.filter(elem => mySearch.indexOf(elem.id) > -1) // filter by id
                      .map(elem => elem.nice_name) // return the nice_name only for each entry
// result is now ['Bill', 'Sam']

答案 1 :(得分:1)

您可以使用Array.prototype.filter()功能:

const data = [ { "id": 10, "nice_name": "Bill" }, 
    { "id": 12, "nice_name": "Dan"}, 
    { "id": 18, "nice_name": "Tony" },
    { "id": 19, "nice_name": "Sam" }, 
]

const result = data.filter(o => ~[10, 19].indexOf(o.id))
// ~[10, 19].indexOf(o.id) is equivalent to [10, 19].indexOf(o.id) > -1

答案 2 :(得分:0)

只使用javascript就可以做到这一点。

console.log

这是一个小提琴https://jsfiddle.net/xo5vxwo0/

答案 3 :(得分:0)

indexOf在数组中查找元素。

arr=[ { "id": 10, "nice_name": "Bill" }, 
    { "id": 12, "nice_name": "Dan"}, 
    { "id": 18, "nice_name": "Tony" },
    { "id": 19, "nice_name": "Sam" }, 
]
var fill=[10,19];
var ans=[];

arr.map(function(a){
    if(fill.indexOf(a["id"])>-1)
    ans.push(a["nice_name"]);
})

console.log(ans);
*{
background-color:pink;
}

答案 4 :(得分:0)

var data = [ { "id": 10, "nice_name": "Bill" }, 
         { "id": 12, "nice_name": "Dan"}, 
         { "id": 18, "nice_name": "Tony" },
         { "id": 19, "nice_name": "Sam" }, 
]

var idWant  = [10,19];
var content = '';   

for(var keysWant in idWant){
    var number = idWant[keysWant];  
    for(var keysData in data){   
        if(number == data[keysData]['id']){   
            content += data[keysData]['nice_name'] + ' ';
        } 
    }  
}  

console.log(content);

答案 5 :(得分:0)

可以使用单个reduce而不是filter.map链。



var arr = [ { "id": 10, "nice_name": "Bill" }, 
            { "id": 12, "nice_name": "Dan"}, 
            { "id": 18, "nice_name": "Tony" },
            { "id": 19, "nice_name": "Sam" }, 
          ],
    src = [10,19],
 result = arr.reduce((r,o) => src.includes(o.id ) ? r.concat(o.nice_name) : r,[]);
console.log(result);