Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Javascript有条件地过滤对象数组_Javascript_Arrays_Hash_Key Value - Fatal编程技术网

使用Javascript有条件地过滤对象数组

使用Javascript有条件地过滤对象数组,javascript,arrays,hash,key-value,Javascript,Arrays,Hash,Key Value,我目前正在处理一个搜索API,其中对象的驱动器值可以是自动或手动 var mixedResults = [{model: "328", drive: "automatic"}, {model: "328", drive: "manual"}, {model: "M4", drive: "automatic"}, {model: "M4", drive: "manual"}]; var linearResults = [{model: "328", drive: "manual"}, {mode

我目前正在处理一个搜索API,其中对象的
驱动器
值可以是
自动
手动

var mixedResults = [{model: "328", drive: "automatic"}, {model: "328", drive: "manual"}, {model: "M4", drive: "automatic"}, {model: "M4", drive: "manual"}];

var linearResults = [{model: "328", drive: "manual"}, {model: "M3", drive: "manual"}];
我要做的是过滤所有具有
自动
的对象,将这些对象保存到变量中,并排除所有其他对象


使用
过滤器可以很容易地做到这一点,但是有一个缺点。如果搜索结果返回的集合中没有一个对象的值为
automatic
,则我想保存
手动
对象的集合。

只需进行筛选并检查是否有空集:

var mixedResults = [{model: "328", drive: "automatic"}, {model: "328", drive: "manual"}, {model: "M4", drive: "automatic"}, {model: "M4", drive: "manual"}];

var results = mixedResults.filter(function (x) {
  return x.drive === "automatic";
});

if (results.length === 0)
  results = mixedResults;

如果您没有
自动
元素,则表示您的整个原始收藏是
手动
。正确。最初的目的是获取任何/所有自动对象,但如果不存在自动对象,则满足于手动对象。您执行过滤。如果得到空集合,则返回原始集合;我建议您将此代码更改为使用3个等号而不是2,因为不需要进行类型转换。条件?@CarlEdwards哪个条件不需要大括号,如果
,则使用
?不,我没用过的地方你都不需要花括号。这个例子在语法上是正确的。@TheWobbuffet我习惯于CoffeeScript,其中
==
==
相同。我几乎写了
results=mixedResults if results.length==0
:|@meagar你一定喜欢咖啡脚本