如何在JavaScript中将包含数组的对象转换为对应元素配对的对象数组
Fixing Syntax Error & Transforming Your Data Structure
First off, let's fix the syntax error in your initial data variable—you're using an array literal ([]) to hold key-value pairs, which isn't valid JavaScript. You should use an object literal ({}) instead:
const data = { fruit: ['apple','banana', 'pear'], // Note: I fixed "peer" to "pear" assuming that's a typo! vegetable: ['tomato','onion', 'leek'] };
Now, to convert this into your desired filteredData structure, we can leverage the fact that both arrays are the same length. Here's a straightforward way to do it:
// Get the keys from the data object const keys = Object.keys(data); // Use the first array to set our loop length reference const firstArray = data[keys[0]]; // Map over each index to build the new objects const filteredData = firstArray.map((_, index) => { return keys.reduce((obj, key) => { obj[key] = data[key][index]; return obj; }, {}); }); console.log(filteredData); // Output: // [ // {fruit: 'apple', vegetable: 'tomato'}, // {fruit: 'banana', vegetable: 'onion'}, // {fruit: 'pear', vegetable: 'leek'} // ]
How this works:
Object.keys(data)grabs the property names ('fruit'and'vegetable') from your data object.- We use the first array's length to loop through each index (this relies on all arrays in your data being the same length—more on that below).
- For each index,
reducebuilds a new object where each key from the original data is assigned the value at that index in its corresponding array.
Important Note:
This approach assumes all arrays in your data object are of equal length. If there's a chance they aren't, you'll want to add a check first to avoid ending up with undefined values in your final objects.
内容的提问来源于stack exchange,提问作者Dongmi Kim
相关产品推荐
相关产品推荐

