簡體   English   中英

遞歸擴展Jquery對象

[英]Extend a Jquery object recursively

我試圖以可重復的方式擴展javascript對象,而不必過多地遍歷我的元素。 這是一個非常簡單的示例來說明問題:

var test1 = [
            {
              tests: [
                {
                  label: "this is a test"
                },
                {
                  label: "this is a test"
                },
                {
                  label: "this is a test"
                }
              ]}];

var test2 = [
            {
              tests: [
                  {comments: 'this is a comment'}
              ]}];

console.log($.extend(true, test1, test2))

http://jsfiddle.net/76bBR/3/

現在,注釋項僅適用於test1中的第一個元素。 我想知道是否有一種巧妙的方法可以使它適用於所有人而不必做forEach。 顯然,在這種小情況下,forEach會很好,但是在我的實際示例中,我有一個非常深的對象,其中包含幾個列表,我想與每個項目的靜態數據合並。 有沒有很酷的工具可以簡化這一過程?

var idealResult = [
            {
              tests: [
                {
                  label: "this is a test",
                  comments: 'this is a comment'
                },
                {
                  label: "this is a test",
                  comments: 'this is a comment'
                },
                {
                  label: "this is a test",
                  comments: 'this is a comment'
                }
              ]}];

這樣嗎 http://jsfiddle.net/76bBR/5/

console.log(test1.concat(test2))

也許您會在這里找到可用的東西: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

我嘗試使用遞歸算法,請參閱jsFiddle

function recursiveAppend(src, dest) {
    // If it's an array, loop through elements
    if ($.isArray(src)) {
        for (var i = 0; i < src.length; i++) {
            // If function returns true, then it found the 'deepest' level...
            if ( recursiveAppend(src[i], dest[i]) ) {
                // ...so extend all objects in the destination...
                for (var j = 0; j < dest.length; j++) {
                    $.extend(true, dest[j], src[i]);
                }
                // ...and stop looping
                break;
            }
        }
    }
    // If it's an object, loop through keys
    else if ($.isPlainObject(src)) {
        for (var key in src) {
            if (src.hasOwnProperty(key)) {
                // Check if the destination has the key
                if (dest.hasOwnProperty(key)) {
                    return recursiveAppend(src[key], dest[key])
                }
                // If it doesn't, then we found the 'deepest' level
                else {
                    //debugger;
                    return true;
                }
            }
        }
    }
    else {
        //debugger;
        return true;
    }
};

該算法假設您的srcdest具有相同的結構(無論它是什么),直到最深層次為止,然后dest將由類似於src的單個對象的對象數組組成。

找到第一個非數組/非對象鍵之后,它也會停止。

它沒有經過完全測試,因此請扔很多隨機測試用例! 您需要添加針對srcdest保護,使其結構不同(我一直假設將有相應的src[i]dest[i]src[key]dest[key] )。

希望這會為您指明正確的方向=)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM