如何使用reduce方法将特定结构的JavaScript对象转换为目标键值对结构?
Great question! Let's fix your reduce implementation to build the target object instead of an array. The key is to use an object as the accumulator (instead of an empty array) and populate it with each attribute key and its values set to false.
Here's the corrected, straightforward implementation:
const attributes = { attributeA: ['valA1', 'valA2'], attributeB: ['valB1'], attributeC: ['valC1', 'valC2', 'valC3'], }; const result = Object.entries(attributes).reduce((acc, [attrKey, attrValues]) => { // Add the main attribute key with value false acc[attrKey] = false; // Loop through each value in the array and add it as a key with false attrValues.forEach(val => { acc[val] = false; }); return acc; }, {}); // Initialize accumulator as an empty object console.log(result);
If you prefer a more concise version using object spreading and Object.fromEntries, this works too:
const result = Object.entries(attributes).reduce((acc, [attrKey, attrValues]) => ({ ...acc, [attrKey]: false, ...Object.fromEntries(attrValues.map(val => [val, false])) }), {});
Why your original code didn't work
Your initial reduce used an empty array as the starting value, so you ended up concatenating all elements into a list instead of building an object. By starting with {} as the accumulator, we can directly assign each required key to it—either via direct property assignment (first example) or by spreading new key-value pairs into the accumulator (second example).
Both approaches will produce exactly the structure you need:
{ attributeA: false, valA1: false, valA2: false, attributeB: false, valB1: false, attributeC: false, valC1: false, valC2: false, valC3: false }
内容的提问来源于stack exchange,提问作者Ricardo Sanchez

