Home >Web Front-end >JS Tutorial >How can I efficiently remove null and undefined attributes from JavaScript objects?
When dealing with data objects, it's often necessary to remove attributes that are not defined or set to null. This article provides solutions for this problem using various JavaScript versions and techniques.
let o = Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));
function removeEmpty(obj) { return Object.fromEntries( Object.entries(obj) .filter(([_, v]) => v != null) .map(([k, v]) => [k, v === Object(v) ? removeEmpty(v) : v]) ); }
Object.keys(obj).forEach((k) => obj[k] == null && delete obj[k]);
let o = Object.keys(obj) .filter((k) => obj[k] != null) .reduce((a, k) => ({ ...a, [k]: obj[k] }), {});
function removeEmpty(obj) { return Object.entries(obj) .filter(([_, v]) => v != null) .reduce((acc, [k, v]) => ({ ...acc, [k]: v === Object(v) ? removeEmpty(v) : v }), {}); }
function removeEmpty(obj) { return Object.keys(obj) .filter(function (k) { return obj[k] != null; }) .reduce(function (acc, k) { acc[k] = obj[k]; return acc; }, {}); }
function removeEmpty(obj) { const newObj = {}; Object.keys(obj).forEach(function (k) { if (obj[k] && typeof obj[k] === "object") { newObj[k] = removeEmpty(obj[k]); } else if (obj[k] != null) { newObj[k] = obj[k]; } }); return newObj; }
function removeEmpty(obj) { return Object.keys(obj) .filter(function (k) { return obj[k] != null; }) .reduce(function (acc, k) { acc[k] = typeof obj[k] === "object" ? removeEmpty(obj[k]) : obj[k]; return acc; }, {}); }
The above is the detailed content of How can I efficiently remove null and undefined attributes from JavaScript objects?. For more information, please follow other related articles on the PHP Chinese website!