You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用reduce方法将特定结构的JavaScript对象转换为目标键值对结构?

Solution to Convert Object Structure Using Reduce

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 16:07:42