javascript - 循环遍历对象并替换值

标签 javascript jquery ajax

我有一个对象,在某些时候有四个级别深,但是我想要一个能够应对引入更多级别的函数。我正在尝试编写一个函数来替换元素,例如 <span class="ajax-parent1-parent2-parent3-value"></span>将替换为 parent1.parent2.parent3.value

问题是深度是可变的,所以我可以有类似 <span class="ajax-parent1-value"></span> 的东西替换为parent1.value

最后,并不总是要替换的文本。可选地,data-attr可以指定要使用的属性(通过 element.attr(<data-attr>, <value>) )。

目前,我正在手动迭代,但是它不是很干净,所以我想知道是否有更好的方法来做到这一点。这对于深度超过两层的情况也不起作用。

function render(data) {
  $.each(data, function(parent, value) {
    $.each(value, function(element, value) {
      $el = $('.ajax-' + parent + '-' + element);
      $.each($el, function(key, el) {
        if ($(el).data('attr')) {
          $(el).attr($(el).data('attr'), value);
        } else {
          $(el).text(value);
        }
      }
    });
  });
}

示例对象:

{
  "profile": {
    "username": "johnd",
    "bio": "Some example data about John",
    "website": "http://john.com",
    "profile_picture": "http://john.com/me.jpg",
    "full_name": "John Doe",
    "counts": {
      "media": 13,
      "followed_by": 26,
      "follows": 49
    },
    "id": "16"
  },
  "dashboard": {
    "script": {
      "tags": ["media"],
      "stats": {
        "liked": 0,
        "lastrun": "never",
        "duration": 0
      },
      "status": {
        "code": 0,
        "slug": "disabled",
        "human": "Disabled",
        "message": "Not running."
      }
    },
    "account": {
      "plan": "free",
      "created": 1419261005373,
      "updated": 1419261005373
    }
  },
  "serverInformation": {
    "serverName": "Johns API",
    "apiVersion": "0.0.1",
    "requestDuration": 22,
    "currentTime": 1419262805646
  },
  "requesterInformation": {
    "id": "redacted",
    "fingerprint": "redacted",
    "remoteIP": "redacted",
    "receivedParams": {
      "action": "getDashboard",
      "apiVersion": 1
    }
  }
}

最佳答案

这是我写的解决方案:

function iterate(obj, stack) {
  for (var property in obj) {
    if (obj.hasOwnProperty(property)) {
      if (typeof obj[property] == "object") {
        iterate(obj[property], stack + '-' + property);
      } else {
        $group = $('.ajax' + stack + '-' + property);
        $.each($group, function(key, element) {
          if ($(element).data('attr')) {
            $(element).attr($(element).data('attr'), obj[property]);
          } else {
            $(element).text(obj[property]);
          }
        });
      }
    }
  }
}

关于javascript - 循环遍历对象并替换值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27606014/

相关文章:

Javascript -function不会在每篇文章后添加段落

jquery - 单击除第一个 td 之外的行

javascript - 无法添加文件以获取 POST 请求

javascript - 如何下载使用base64 url​​编码的div背景

javascript - 以编程方式对 Chrome 堆进行快照

javascript - 如何将 JSON 发送到我的 python 脚本?

c# - 当用户按下 Enter 键而文本框具有焦点时,ASP MVC、jQuery 问题在 ajax post 上返回错误

Javascript:正确的闭包语法和格式

javascript - jQuery Accordion 插件(如 Facebook 或 Google)

php - jquery ajax - 更好地返回 json 或纯 html