草庐IT

javascript - 为每个 JSON 数据记录添加对象

coder 2024-05-17 原文

如何根据如下所示的 JSON 数据向代码片段中的以下恒星系统添加新元素(我指的是行星):

        [{
           "rowid": 1,
           "Radius size": 3 ,
           "Distance": 110 pixels,
        },
         {
           "rowid": 2,
           "Size": 2.5,
           "Distance": 120 pixels,
        }]

每一行 ID 都是它自己的行星,具有自己的大小和位置。该距离当然基于行星与位于页面中心的太阳元素的距离。每个行星的距离需要处于不同的 Angular ,否则它们都会完美排列(不现实)。关于如何实现这一目标的任何想法?

var ball = {};

function makeBall(spec) {
  // Create the element
  var circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
  // Set its various attributes
  ["id", "cx", "cy", "r", "class"].forEach(function(attrName) {
    if (spec.element[attrName]) {
      circle.setAttribute(attrName, spec.element[attrName]);
    }
  });
  // Add it to the sun
  document.getElementById("Sun2").appendChild(circle);
  // Remember its animation settings in `ball`
  ball[spec.element.id] = spec.animation;
}

function addObject() {
  // Create a spec to use with makeBall from the fields
  var spec = {
    element: {
      id: document.getElementById("new-id").value,
      class: document.getElementById("new-class").value,
      r: parseFloat(document.getElementById("new-r").value)
    },
    animation: {
      speed: 2,
      spin: 30,
      side: 40
    }
  };
  // Some minimal validation
  if (!spec.element.id || !spec.element.r || !spec.animation.speed || !spec.animation.spin || isNaN(spec.animation.side)) {
    alert("Need all values to add a ball");
  } else if (ball[spec.element.id]) {
    alert("There is already a ball '" + spec.element.id + "'");
  } else {
    // Do it!
    makeBall(spec);
  }
}

function rotation(coorX, coorY, object) {
  object.side += (1.0 / object.speed);
  var ang = object.side * 2.0 * Math.PI / 180.0;
  var r = object.spin;

  return {
    x: Math.cos(ang) * r - Math.sin(ang) * r + coorX,
    y: Math.sin(ang) * r + Math.cos(ang) * r + coorY
  };
}

function rotationball(circle) {
  var x, y, x_black, y_black, e, newpos, black;

  // We always rotate around black
  black = document.getElementById("black");
  
  // Get this circle and update its position
  e = document.getElementById(circle);
  x_black = parseFloat(black.getAttribute("cx"));
  y_black = parseFloat(black.getAttribute("cy"));
  newpos = rotation(x_black, y_black, ball[circle]);

  e.setAttribute("cx", newpos.x);
  e.setAttribute("cy", newpos.y);
}

function animate() {
  Object.keys(ball).forEach(function(id) {
    rotationball(id);
  });
}

var animateInterval = setInterval(animate, 1000 / 60);
.st0 {
  fill: yellow;
}

.st1 {
  fill: orange;
}
<div>Add ball:
  <label>
    ID: <input type="text" id="new-id" value="newball">
  </label>
  <label>
    R: <input type="text" id="new-r" value="10">
  </label>
  <label>
    Speed: <input type="text" id="new-speed" value="1.2">
  </label>
  <label>
    Spin: <input type="text" id="new-spin" value="80">
  </label>
  <label>
    Side: <input type="text" id="new-side" value="0.0">
  </label>
  <label>
    Class: <input type="text" id="new-class" value="st1">
  </label>
  <button type="button" onclick="addObject()">
    Make Ball
  </button>
</div>

<div class="spinning">
  <svg xmlns="http://www.w3.org/2000/svg" id="solly" viewBox="0 0 1000 600">
    <g id="Sun2">
      <circle id="black" class="st0" cx="500" cy="300.8" r="10" />
    </g>
  </svg>
</div>
上面是代码(不完全是我的),如果它有自己的 ID,它会添加新的球(行星)。我只想用 JSON 数据集来切换它。

编辑: 以下是两个记录的原始示例。如您所见,它提供了更多但多余的属性。我真正需要的是每条记录的大小(行星半径 [木星半径] 和距离(距离 [pc])。距离需要转换为像素,大小比较棘手。

     [{
       "rowid": 1,
       "Host name": "TrES-3",
       "Number of Planets in System": 1,
       "Planet Mass or M*sin(i)[Jupiter mass]": 1.91,
       "Planet Radius [Jupiter radii]": 1.336,
       "Planet Density [g": {
          "cm**3]": 0.994
       },
       "Distance [pc]": 228,
       "Effective Temperature [K]": 5650,
       "Date of Last Update": "5/14/2014"
    },
     {
       "rowid": 2,
       "Host name": "UZ For",
       "Number of Planets in System": 2,
       "Planet Mass or M*sin(i)[Jupiter mass]": 6.3,
       "Planet Radius [Jupiter radii]": null,
       "Planet Density [g": {
          "cm**3]": null
       },
       "Distance [pc]": null,
       "Effective Temperature [K]": null,
       "Date of Last Update": "5/14/2014"
    }]

最佳答案

其实很简单:

如果您通读 HTML,您会注意到单击“制作球”按钮将调用 addObject()。所以你去检查 JS 代码中的那个函数。 addObject() 只是将输入字段中的值解析为一个名为 spec 的对象,然后调用 makeBall(spec)。

您需要做的是为每个 JSON 数据的 makeBall 函数提供完全相同的数据对象规范。

function addObjectsFromJson(json){
    // using try catch block because JSON.parse will throw an error if the json is malformed
    try{
        var array = JSON.parse(json);
        for(var i = 0; i < array.length; i++){
            var planet = array[i];
            // create a spec to use with makeBall from the json
            var spec = {
                element: {
                    id: planet.rowid,
                    // you don't provide a style class in your json yet, using yellow as default
                    class: 'st0',
                    // your json must have a standard property for radius,
                    // currently you have "Radius size" (is wrong since
                    // properties cannot have spaces) and "Size"
                    r: planet["Planet Radius [Jupiter radii]"]
                },
                animation: {
                    speed: 2,
                    spin: 30,
                    side: planet["Distance [pc]"]
                }
            };
            makeBall(spec);
        }
    }catch(e){
        console.log('error: ' + e);
    }
}

虽然我没有在 makeBall() 函数中看到用于添加距离的属性。

使用 jQuery 通过 ajax 处理 JSON:

// assuming your local server runs on port 8080
$.getJSON('localhost:8080/path/to/your/file', function (json) {
    // since we use getJSON, it is already parsed and a javascript object
    // additional parsing inside the addObjectsFromJson function is not necassary
    // and would throw an error
    addObjectsFromJson(json);
});

function addObjectsFromJson(json) {
    for (var i = 0; i < json.length; i++) {
        var planet = json[i];
        // create a spec to use with makeBall from the json
        var spec = {
            element: {
                id: planet.rowid,
                // you don't provide a style class in your json yet, using yellow as default
                class: 'st0',
                // your json must have a standard property for radius,
                // currently you have "Radius size" (is wrong since properties cannot have spaces) and "Size"
                    r: planet["Planet Radius [Jupiter radii]"]
                },
                animation: {
                    speed: 2,
                    spin: 30,
                    side: planet["Distance [pc]"]
        };
        makeBall(spec);
    }
}

关于javascript - 为每个 JSON 数据记录添加对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39243864/

有关javascript - 为每个 JSON 数据记录添加对象的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  3. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  4. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  5. ruby - 将 Bootstrap Less 添加到 Sinatra - 2

    我有一个ModularSinatra应用程序,我正在尝试将Bootstrap添加到应用程序中。get'/bootstrap/application.css'doless:"bootstrap/bootstrap"end我在views/bootstrap中有所有less文件,包括bootstrap.less。我收到这个错误:Less::ParseErrorat/bootstrap/application.css'reset.less'wasn'tfound.Bootstrap.less的第一行是://CSSReset@import"reset.less";我尝试了所有不同的路径格式,但它

  6. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  7. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

  8. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  9. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  10. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

随机推荐