循环遍历对象并替换值

时间:2014-12-22 15:53:14

标签: 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
    }
  }
}

2 个答案:

答案 0 :(得分: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]);
          }
        });
      }
    }
  }
}

答案 1 :(得分:0)

为什么不从HTML开始,因此您只能访问实际想要呈现的属性?

这样你可以保持它非常简单(同时请注意,这消除了以与数据对象相同的顺序/深度嵌套HTML跨度的需要,你可以将任何HTML节点放在任何地方。只是确保你没有多次使用类/节点名称。

function parseData(data) {
    var $container = $('.ajax');

    $container.find("[class^='ajax-']").each(function(i, el) {
        var $el = $(el);
        if ($el.children().length === 0)
        {
            var nodes = $el.attr('class').split('-');
            nodes.shift();

            var node = data;
            for (var i = 0; i < nodes.length; i++) {
                node = node[nodes[i]];

                if (typeof(node) == "undefined") {
                    break;
                }
            }

            if ($el.data('attr'))
            {
                $el.attr($el.data('attr'), node);
            }
            else
            {
                $el.text(node);
            }
        }
    });
}

小提琴:

http://jsfiddle.net/ckcduLhn/5/

相关问题