全部,
我有两个数组如下:
var arr1 = [ '1956888670', '2109171907', '298845084' ];
var arr2 = [
{ KEY: '1262875245', VALUE: 'Vijay Kumar Verma' },
{ KEY: '1956888670', VALUE: 'Sivakesava Nallam' },
{ KEY: '2109171907', VALUE: 'udm analyst' },
{ KEY: '298845084', VALUE: 'Mukesh Nagora' },
{ KEY: '2007285563', VALUE: 'Yang Liu' },
{ KEY: '1976156380', VALUE: 'Imtiaz Zafar' },
];
arr1有键,arr2有键和值。 我想输出arr1中存在的那些键的键和值。 因此我的输出应该是,
[{ KEY: '1956888670', VALUE: 'Sivakesava Nallam' },
{ KEY: '2109171907', VALUE: 'udm analyst' },
{ KEY: '298845084', VALUE: 'Mukesh Nagora' },]
请求您的帮助以编写一个函数来使用javascript.Thanks提前获取所需的输出。
答案 0 :(得分:1)
var arr1 = [ '1956888670', '2109171907', '298845084' ];
var arr2 = [
{ KEY: '1262875245', VALUE: 'Vijay Kumar Verma' },
{ KEY: '1956888670', VALUE: 'Sivakesava Nallam' },
{ KEY: '2109171907', VALUE: 'udm analyst' },
{ KEY: '298845084', VALUE: 'Mukesh Nagora' },
{ KEY: '2007285563', VALUE: 'Yang Liu' },
{ KEY: '1976156380', VALUE: 'Imtiaz Zafar' },
];
result = arr2.filter( function(obj) {
return arr1.indexOf(obj.KEY) >= 0;
});
console.info(result);
答案 1 :(得分:0)
您可以尝试使用filter
- Array.prototype.filter()
:
var output = arr2.filter(function(item) {
return arr1.indexOf(item.KEY) >= 0;
});
答案 2 :(得分:0)
您可以使用Set
进行过滤。
var arr1 = ['1956888670', '2109171907', '298845084'],
arr2 = [{ KEY: '1262875245', VALUE: 'Vijay Kumar Verma' }, { KEY: '1956888670', VALUE: 'Sivakesava Nallam' }, { KEY: '2109171907', VALUE: 'udm nalyst' }, { KEY: '298845084', VALUE: 'Mukesh Nagora' }, { KEY: '2007285563', ALUE: 'Yang Liu' }, { KEY: '1976156380', VALUE: 'Imtiaz Zafar' }],
mySet = new Set,
result;
arr1.forEach(function (a) {
mySet.add(a);
});
result = arr2.filter(function (a) {
return mySet.has(a.KEY);
});
console.log(result);