【问题标题】:Replace object value with other object's value of the same key with JavaScript用 JavaScript 将对象值替换为具有相同键的其他对象的值
【发布时间】:2015-10-09 15:02:16
【问题描述】:

我有两个对象,itemresults。 它们都有相同的键,但可能有不同的值,例如:

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

【问题讨论】:

  • 循环遍历对象。或者,如果您使用的是 jQuery,请查看合并。
  • 你可以使用 angulars $filter,或者使用 lodash,或者使用原生的 .map。选择你的毒药!
  • @BartekBanachewicz 谢谢你是对的。我之前看到过这个问题,但误解了我自己的问题。

标签: javascript object


【解决方案1】:

它可以解决问题!

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);
&lt;div id='dbg'&gt;&lt;/div&gt;

【讨论】:

    【解决方案2】:

    你可以优雅地使用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));
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"&gt;&lt;/script&gt;

    请注意,请求的值现在在结果中(而不是在项目中)。如果您仍然需要它,请将这些值克隆到一个新变量中并使用它。

    【讨论】:

    • lodash 是处理数组和对象时非常有用的库。
    【解决方案3】:

    您可以像这样遍历对象。 hasOwnProperty 测试它是否是您定义的属性,而不是来自基础对象定义的属性。

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

    【讨论】:

      【解决方案4】:

      您也可以使用nullish coalescing operator 来简化一下。

      var item = {
        id: '50',
        area: 'Mexico',
        gender: null,
        birthdate: null
      };
      var results={
        id: '50',
        area: null,
        gender: 'Male',
        birthdate: null
      };
      
      Object.keys(item).forEach(function(key) {
        item[key] = item[key] ?? results[key];
      })
      
      document.getElementById('dbg').innerHTML ='<pre>' + JSON.stringify(item , null , ' ') + '</pre>';
      
      console.dir(item);
      &lt;div id='dbg'&gt;&lt;/div&gt;

      【讨论】:

        【解决方案5】:

        旧帖子,但如果您搜索更新的直接解决方案,您可以尝试Object.assign()。如果目标对象中的属性具有相同的键,它们将被源中的属性覆盖。

        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 }
        

        【讨论】:

          【解决方案6】:

          您可以只迭代所有对象键,然后将它们分配给每个项目:

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

          【讨论】:

            【解决方案7】:

            对于一个班轮,这是一个选项:

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

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2020-08-23
              • 2022-07-26
              • 2022-08-18
              • 2019-11-02
              • 2022-11-18
              • 2017-06-24
              • 1970-01-01
              • 2022-11-01
              相关资源
              最近更新 更多