15

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] 
    }             
}
4
  • Loop over the object. Or if you are using jQuery, look at merge. Commented Oct 9, 2015 at 15:04
  • 1
    Possible duplicate of Loop through JavaScript object Commented Oct 9, 2015 at 15:05
  • You could do this using angulars $filter, or using lodash, or using the native .map. Choose your poison! Commented Oct 9, 2015 at 15:06
  • @BartekBanachewicz Thanks you were right. I saw that question before but misunderstood my own problem. Commented Oct 12, 2015 at 8:01

7 Answers 7

15

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>

Sign up to request clarification or add additional context in comments.

Comments

4

You can elegantly use 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>

Note that the requested value is now in results (and not in item). If you still need it item, clone the values into a new variable and use it.

1 Comment

lodash is very helpful library when working with arrays and objects.
2

You can loop over the object like this. hasOwnProperty tests if it is a property defined by you and not from the base object definition.

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

Comments

2

Old post but if you search a more recent straightforward solution you can try Object.assign(). Properties in the target object are overwritten by properties in the sources if they have the same key.

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);

console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }

console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }

Comments

2

You can also use the nullish coalescing operator and a reduce function to simplify it a bit.

var item = {
  id: '50',
  area: 'Mexico',
  gender: null,
  birthdate: null
};
var results={
  id: '50',
  area: null,
  gender: 'Male',
  birthdate: null
};

item = Object.keys(item).reduce((acc, key) => {
  acc[key] = acc[key] ?? results[key];
  return acc;
}, item);

document.getElementById('dbg').innerHTML ='<pre>' + JSON.stringify(item , null , ' ') + '</pre>';

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

1 Comment

I replaced the forEach with a reduce to avoid mutations. Lovely solution.
1

For the one liner, here is an option:

{ ...item, ...Object.keys(results).reduce((pv, cv) => results[cv] == null ? pv : { ...pv, [cv]: results[cv] }, {}) };

Comments

0

You could just iterate all the object keys, and then write assign them on each item:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.