如何将对象数组转换为移除ID/flag的指定结构二维数组
Clean Solution for Formatting Your Object Array into a 2D Array
Hey there! I totally get why your original approach feels clunky—manually splicing keys can be error-prone and hard to read. Let's go with a more straightforward, maintainable solution that guarantees your data lines up perfectly with the desired headers.
The Optimal Approach
Instead of removing unwanted keys from the object's key list, we'll explicitly define the headers we want (this also lets us control their order exactly). Then we'll map over your original data array to extract values in that exact order.
Here's the code:
const data = [ {"ID":1,"process":"quick","owner":"John","decission":"Admin","status":"failed","flag":"red"}, {"ID":2,"process":"standard","owner":"Mary","decission":"Admin","status":"failed","flag":"blue"}, {"ID":3,"process":"slow","owner":"John","decission":"Management","status":"active","flag":"red"} ]; // Define the exact headers we want to keep (no need to delete anything!) const desiredHeaders = ['process', 'owner', 'decission', 'status']; // Build the formatted array: start with headers, then map each item to match the header order const formattedArray = [ desiredHeaders, ...data.map(item => desiredHeaders.map(headerKey => item[headerKey])) ]; console.log(formattedArray);
Why This Works Better Than Your Original Method
- Controlled Order: By explicitly listing
desiredHeaders, you're guaranteed the header and data rows stay in the exact order you want—no surprises from object key ordering (even though modern JS objects preserve insertion order, explicit is always safer). - Cleaner & More Readable: No messy
splicecalls or index hunting. Anyone reading the code can immediately see which fields are being included. - Maintainable: If you ever need to add/remove/reorder headers, you just update the
desiredHeadersarray—no other changes required. - Immutable: Unlike
splice(which modifies the original array), this approach usesmapto create new arrays, avoiding unintended side effects.
This will output exactly the 2D array you're looking for:
[ ["process","owner","decission","status"], ["quick","John","Admin","failed"], ["standard","Mary","Admin","failed"], ["slow","John","Management","active"] ]
内容的提问来源于stack exchange,提问作者katie hudson
相关产品推荐
相关产品推荐

