【问题标题】:How to combine complicated JSON objects in Javascript如何在 Javascript 中组合复杂的 JSON 对象
【发布时间】:2022-06-14 23:23:20
【问题描述】:

我正在使用 Cytoscape JS 制作网络查看器,为此我需要通过 JSON 对象提供样式。我基本上想要一个热图,所以我在 255 个类别中选择它们,每个类别都有自己的颜色。由于我不打算写 255 个条目,我想用循环来完成。然而,这种结合让我很头疼,我真的不知道我在哪里愚蠢。

var create_stylesheet = function(){
        var to_return =[
            {
                'selector': 'node', 'style': {'content': 'data(label)', 'background-color': 'BlueViolet'}
            },
            {
                'selector': 'edge', 'style': {'label': 'data(score)'}
            }]; // <- this entry is for basic node labels and stuff. It needs to be first.
     
        //For loop that assigns a colour to each category.
        //As the red RGB value goes up, the blue RGB goes down. creating a gradient from cold to warm. 
        // In the program warmer colours have a higher score. 
        for(i = 0; i <= 255; i++){
            var cat = `.cat_${i}`;
            var colour = `rgb(${i}, 0, ${255-i})`;
            var to_append =
               {
                   'selector': cat, 'style': {'line-color': colour}
               };

              //Here I'd like to add to_append to the to_return variable. 
        }
        

        return to_return; //Return the finished stylesheet.
    }

谢谢,非常感谢您的帮助。

【问题讨论】:

  • 你为什么要写 JSON?只需创建标准的 JS 对象,然后使用 JSON.stringify() 最后获取 JSON。
  • 您的 to_return 变量是一个数组,所以为什么不直接将新的 to_append 值推送给它。 to_return.push(to_append)

标签: javascript json iteration combine


猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-11
  • 2017-07-10
  • 2019-08-27
  • 2020-12-15
相关资源
最近更新 更多