js过滤出对象中想要的数据

/**
	 * [过滤对象]
	 * @param  obj [过滤前数据]
	 * @param  arr [过滤条件,要求为数组]
	 */
	function filterObj(obj, arr) {
		if (typeof (obj) !== "object" || !Array.isArray(arr)) {
			throw new Error("参数格式不正确")
		}
		const result = {}
		Object.keys(obj).filter((key) => arr.includes(key)).forEach((key) => {
			result[key] = obj[key]
		})
		return result
	}

/**
使用
**/

let obj = {
    a: '1',
    b: '2',
    c: '3'
}

let newObj = filterObj(obj,["a", "b"]);

返回结果 :

newObj{
    a: '1',
    b: '2'
}

猜你喜欢

转载自blog.csdn.net/qq_33401924/article/details/88398449