Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
132
rated 0 times [  135] [ 3]  / answers: 1 / hits: 73688  / 9 Years ago, fri, october 9, 2015, 12:00:00

I've got two objects, item and results.
They've both got the same keys but possibly different values, for example:



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

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


What I want to do is exactly the following:



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


but I'm looking for a way to do this for each value of my item object. You know, without having to write a huge function if my objects happen to have a lot more keys / values.
Any ideas?



Update : I misunderstood my own problem and the only issue was that I didnt really understand how to get an object value given a certain key. I couldnt really use any outside scripts or divs since Im using Azure's mobile service scripts.



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

More From » object

 Answers
3

It could do the trick !





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>




[#64785] Wednesday, October 7, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
arthur

Total Points: 729
Total Questions: 107
Total Answers: 109

Location: China
Member since Mon, Aug 22, 2022
2 Years ago
;