Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace object value with other object's value of the same key with JavaScript

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] 
    }             
}
like image 553
Luuk Gortzak Avatar asked Oct 09 '15 15:10

Luuk Gortzak


1 Answers

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>
like image 161
Anonymous0day Avatar answered Oct 18 '22 09:10

Anonymous0day