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

基于字典键值对动态生成JSON的JavaScript实现疑问

Solution to Build Your Highlighted Color Object

It looks like you're almost there! The main issue with your current code is that you're creating a new empty item object every iteration of the forEach loop, but you're not accumulating those key-value pairs into a single final object. Here's how to fix it:

  • Initialize your target object first: Create the empty highlighted_color object outside the loop so it persists across iterations.
  • Populate the object in the loop: Instead of making a new item each time, assign each key-value pair directly to your target object.

Here's the corrected code:

// Start with an empty object to build on
var highlighted_color = {};

// Iterate over each entry in your data object
Object.entries(data).forEach(([key, value]) => {
  // Add each key-color pair to the target object
  highlighted_color[key] = value;
});

// Now highlighted_color matches your desired structure!
console.log(highlighted_color);

Shorter Alternatives (If Applicable)

If your data object already contains exactly the keys and values you need (no extra properties to exclude), you can use these concise methods instead of a loop:

  • Object spread syntax:
    var highlighted_color = {...data};
    
  • Object.assign:
    var highlighted_color = Object.assign({}, data);
    

A quick note: I renamed values to value in the loop since each entry gives a single color value—it makes the code a bit more readable and accurate!

内容的提问来源于stack exchange,提问作者Alan John J

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 19:47:41