什么是从数组中过滤对象所需的最简单的JavaScript [英] What is the briefest JavaScript necessary to filter objects from an array

查看:99
本文介绍了什么是从数组中过滤对象所需的最简单的JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定数组

let arr = [1,2,true,4,{"abc":123},6,7,{"def":456},9,[10],{},"[object Object]"];
/*
let res = // briefest `javascript` text to filter objects from `arr`
*/

预期结果 res

[{"abc":123},{"def":456},{}];

什么是必需的简短 javascript 从原始数组中过滤对象?

What is the briefest javascript text necessary to filter objects from the original array?

推荐答案

可以使用 Array.prototype.filter() code>。从匹配中排除字符串[object Object],使用''+元素将元素转换为字符串,返回 Boolean 使用identity运算符的元素的结果,该元素作为字符串等于[object Object]

You can use Array.prototype.filter(). Exclude string "[object Object]" from matches, cast element to string with ''+element, return Boolean result of check using identity operator that element as string is equal to "[object Object]"

let arr = [1,2,true,4,{"abc":123},6,7,{"def":456},9,[10],{},"[object Object]"];

let res = arr.filter(o=>''+{}!==o&&''+o===''+{});

console.log(res);

这篇关于什么是从数组中过滤对象所需的最简单的JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆