2015-09-03 83 views
1

我正在處理這個JS文件,它以JSON格式返回值。 我需要在每個字符串值的開始和結尾都有一個成員函數append @。我無法弄清楚如何做到這一點。文件的內容是這樣的,但可能有任何數量的對象修改每個JSON對象的值

var SomeText = function() { 
    return { 
     "CommonText": 
     { 
      "ViewAll": "View All", 
      "SignOut": "Sign out", 
      "More": "More", 
      "New": "New" 
     }, 
     "ErrorText": { 
      "Tag": "Error !", 
      "EmptyGridMessage": "You do not have any {0}" 
     }, 
    }; 
}; 

這裏我需要在每個字符串值附加@。例如。對於標記/錯誤名稱值對,我需要將其轉換爲「@Error!@」。

+0

所以要值轉換函數被調用或函數本身 – Flake

+0

內的轉換應該是函數自身內部後。 –

+0

請重新閱讀我的問題修正版 – mplungjan

回答

3

這裏是這樣做使用遞歸一個通用的方法,不像其他的解決方案,它會改變所有字符串的對象,不管他們是什麼級別:

var myObj = { 
     "CommonText": 
     { 
      "ViewAll": "View All", 
      "SignOut": "Sign out", 
      "More": "More", 
      "New": "New" 
     }, 
     "ErrorText": { 
      "Tag": "Error !", 
      "EmptyGridMessage": "You do not have any {0}" 
     }, 
    }; 
    function deepStringConcat(myObj) { 
     function walker(obj) { 
      var k, has = Object.prototype.hasOwnProperty.bind(obj); 
      for (k in obj) if (has(k)) { 
       switch (typeof obj[k]) { 
        case 'object': 
         walker(obj[k]); break; 
        case 'string': 
         obj[k] = '@' + obj[k] + '@'; 
       } 
      } 
     } 
     walker(myObj); 
    }; 
    deepStringConcat(myObj); 
    console.log(myObj); 

Fiddle

+0

這是一個不錯的解決方案。我也在考慮遞歸,但你快一分鐘。你錯過的只是在字符串的末尾附加「@」。 – cezar

+0

我喜歡有()綁定:) – mplungjan

+0

@cezar沒有什麼像一個很好的遞歸開始一天:)關於其他@,我錯過了,修復。 – Black0ut

1

這裏我的解決方案,使用遞歸函數將@僅添加到字符串並遍歷對象。

function appendAt (text) { 
    for (var t in text) { 
     if (text.hasOwnProperty(t) && typeof text[t] === "string") { 
      text[t] = '@' + text[t] + '@'; 
     } 
     if (typeof text[t] === "object") { 
      appendAt(text[t]); 
     } 
    } 
    return text; 
} 

// run the function 
var text = SomeText(); 
console.log(text); // normal output 
appendAt(text); 
console.log(text); // output with appended @ at begin/end of each string 
+0

謝謝!你是對的。我只是忽略了這個問題,因爲被質疑的對象是JSON格式的,我沒有在原型鏈中假設任何東西,所以我想盡可能保持簡單。 – cezar

+0

是的,我測試過它(編輯之前和之後)。你是否指出主要的原型。在這個例子中'hasOwnProperty'也被繼承。 – cezar

+0

@mplungjan Ik begrijp je;)這是讓我困惑的問號。 – cezar

1

你可以嘗試這樣的事情。它只會改變第一級由你的問題所示:

// get the object returned by SomeText 
var output = SomeText(); 

// for each object property rewrite the value 
// using the updateObject function 
Object.keys(output).forEach(function (obj) { 
    output[obj] = updateObject(output[obj]); 
}); 

function updateObject(obj) { 

    // for each property in the object, update the value 
    Object.keys(obj).forEach(function (el) { 
    obj[el] = '@' + obj[el] + '@'; 
    }); 
    return obj; 
} 

DEMO

+0

很高興在JavaScript中看到OOP的高級用法,但不幸的是,它返回了諸如「Tag」:「@ Tag @」這樣的項,它應該是「Tag」:「@Error!@」 – cezar

+0

@cezar , 謝謝。愚蠢的錯誤。 – Andy