使用JavaScript将对象值替换为相同键的其他对象的值 [英] Replace object value with other object's value of the same key with JavaScript

查看:102
本文介绍了使用JavaScript将对象值替换为相同键的其他对象的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个对象, item results
他们都有相同的键,但可能有不同的值,例如:

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;
}

但我正在寻找一种方法来为我的每个值做这个 item object。你知道,如果我的对象碰巧有更多的键/值,就不必写一个巨大的函数。
有什么想法吗?

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?

更新:我误解了自己的问题,唯一的问题是我并没有真正理解如何在给定某个键的情况下获取对象值。因为我使用Azure的移动服务脚本,所以我无法真正使用任何外部脚本或div。

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] 
    }             
}


推荐答案

它可以做到这一点!

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>

这篇关于使用JavaScript将对象值替换为相同键的其他对象的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆