基于字典键值对动态生成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_colorobject outside the loop so it persists across iterations. - Populate the object in the loop: Instead of making a new
itemeach 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
相关产品推荐
相关产品推荐

