如何过滤对象数组以匹配列表?

时间:2018-01-11 23:52:50

标签: javascript json

鉴于400.000这样的大数据:

var data = [
 {
  "kDefinition": "ford stream, wade across", 
  "kMandarin": "shè", 
  "char": "涉", 
  "kCantonese": "sip3", 
  "kJapaneseKun": "WATARU KAKAWARU", 
 }, 
 {
  "kDefinition": "to pierce, to stab; to take", 
  "kMandarin": "jué", 
  "char": "鈌", 
  "kCantonese": "kyut3", 
  "kJapaneseKun": "SASU"
 },
 ...
]

给出一个较小的1000单位子集列表,其匹配char字段为:

var list = ['早', '维', '基', '涉', '百', ..., '科', '月']  

如何将较大的数据减少到只保留obj.charlist出现的1000个对象?

修改: listdata的排序顺序不同。

2 个答案:

答案 0 :(得分:3)

您可以将list数组转换为Set,然后按照@Amadan的建议在过滤器中使用has()方法。



var data = [{"kDefinition":"ford stream, wade across","kMandarin":"shè","char":"涉","kCantonese":"sip3","kJapaneseKun":"WATARU KAKAWARU"},{"kDefinition":"to pierce, to stab; to take","kMandarin":"jué","char":"鈌","kCantonese":"kyut3","kJapaneseKun":"SASU"}]
var list = ['早', '维', '基', '涉', '百', '科', '月']  

list = new Set(list)

const result = data.filter(({char}) => list.has(char));
console.log(result)




答案 1 :(得分:1)

对于这个大小的列表,我会考虑使用旧的学校循环。它通常是最快的,它几乎就像任何更现代的解决方案一样容易。

var data = [
 {
  "kDefinition": "ford stream, wade across", 
  "kMandarin": "shè", 
  "char": "涉", 
  "kCantonese": "sip3", 
  "kJapaneseKun": "WATARU KAKAWARU", 
 }, 
 {
  "kDefinition": "to pierce, to stab; to take", 
  "kMandarin": "jué", 
  "char": "鈌", 
  "kCantonese": "kyut3", 
  "kJapaneseKun": "SASU"
 }
];

var list = [ '早', '维', '基', '涉', '百', '科', '月' ];

// First, make an object from the char list
var chars = {};
for( var i = 0, n = list.length;  i < n;  ++i ) {
    chars[ list[i] ] = true;
}

// Now we can match against the data
var output = [];
for( var i = 0, n = data.length;  i < n;  ++i ) {
    if( chars.hasOwnProperty( data[i].char ) ) {
        output.push( data[i] );
    }
}

console.log( JSON.stringify( output, null, 4 ) );