2015-10-09 58 views
3

我有兩個對象itemresults。 他們已經都得到了相同的密鑰,但可能有不同的值,例如:用JavaScript替換對象值與同一個鍵的其他對象的值

item.id = '50' 
item.area = 'Mexico' 
item.gender = null 
item.birthdate = null 

results.id = '50' 
results.area = null 
results.gender = 'Male' 
results.birthdate = null 

我想要做的是完全以下:

if (item.id == null || items.id == 0) 
{ 
    item.id = results.id; 
} 

但我正在尋找一種方式來爲我的item對象的每個值執行此操作。你知道,如果我的對象碰巧有更多的鍵/值,不必編寫一個巨大的函數。 任何想法?

更新:我誤解了我自己的問題,唯一的問題是,我真的不明白如何獲得一個給定的關鍵對象值。自從使用Azure的移動服務腳本以來,我無法真正使用任何外部腳本或div。

for (var key in item) { 
    if(item[key] == null || item[key] == 0){ 
     item[key] = results[0][key] 
    }    
} 
+0

在對象上循環。或者如果你使用jQuery,看看合併。 – epascarello

+1

[通過JavaScript對象循環]的可能重複(http://stackoverflow.com/questions/684672/loop-through-javascript-object) –

+0

您可以使用angulars'$ filter'或使用lodash或使用原生的'.map'。選擇你的毒藥! – Fuser97381

回答

2

它可以做的伎倆!

var item = {}; 
 
var results={}; 
 

 
item.id = '50' 
 
item.area = 'Mexico' 
 
item.gender = null 
 
item.birthdate = null 
 

 
results.id = '50' 
 
results.area = null 
 
results.gender = 'Male' 
 
results.birthdate = null 
 

 
Object.keys(item).forEach(function(key) { 
 
    if (item[key] == null || item[key] == 0) { 
 
    item[key] = results[key]; 
 
    } 
 
}) 
 
document.getElementById('dbg').innerHTML ='<pre>' + JSON.stringify(item , null , ' ') + '</pre>'; 
 

 
console.dir(item);
<div id='dbg'></div>

+0

謝謝。這就是我需要:)更新我的問題以及 –

+0

不客氣! :-) – Anonymous0day

-1

你可以只遍歷所有的對象鍵,然後寫爲它們分配在各個項目上:

for (var property in results) { 
    if (results.hasOwnProperty(property) && !item[property]) { 
     // do stuff 
     item[property] = results[property] 
    } 
} 
1

你也可以遍歷這樣的對象。 hasOwnProperty測試它是否是您定義的屬性,而不是基礎對象定義。

for (var key in item) { 
    if (item.hasOwnProperty(key)) { 
     if (item[key] == null) { 
      item[key] = results[key]; 
     } 
    } 
} 
0

您可以用優雅lodash

var results = {}; 
 
var item = {}; 
 

 
item.id = '50'; 
 
item.area = 'Mexico'; 
 
item.gender = null; 
 
item.birthdate = null; 
 

 
results.id = '50'; 
 
results.area = null; 
 
results.gender = 'Male'; 
 
results.birthdate = null; 
 

 
_.merge(results, _.pick(item, _.identity)); 
 

 
alert(JSON.stringify(results));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>

注意,請求值現在是結果(而不是項目)。如果您仍然需要它,請將這些值複製到一個新變量中並使用它。

相關問題