从对象中删除默认值 [英] remove default values from an object

查看:106
本文介绍了从对象中删除默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个javascript对象:

I have two javascript objects:

var a = {
    x: 1, 
    y: {
        faz: 'hello', 
        baz: ''
    },
    z: [1, 2]
};


var defaults = {
    x: 2,
    y: {
        faz: '', 
        baz: ''
    },
    z: [1, 2]
};

我想只保留的字段默认情况下不同

I want to only keep the fields of a that are different from the default:

a = remove_defaults(a, defaults); // <---- i need this fnc
{
    x: 1,
    y: {
        faz: 'hello'
    }
}

目标是从作为状态的对象中删除默认值(通过URL)。状态可以有嵌套字段,因此浅层比较是不够的。叶子值都是原始的(数字,字符串,bool)。

The goal is to remove default values from an object that serves as a state (via URL). The state can have nested fields, so a shallow compare is not enough. The leaf values are all primitive (number, string, bool).

(这有点像 undercore.js的反面's _。默认值()方法)

(this is a bit like the opposite of underscore.js's _.defaults() method)

什么是实现这个目标的最佳方法是?

What is the best way to achieve this?

解决方案可以使用 underscore.js 如果有帮助,但没有 jquery

The solution can use underscore.js if that helps, but no jquery.

推荐答案

尝试这个:

function removeDuplicates(a, defaults, result) {
  for (var i in a) {
    if (i in defaults) {
      if (typeof a[i] == "object" 
          && typeof defaults[i] == "object"
          && Object.prototype.toString.call(defaults[i]) !== '[object Array]') {
        result[i] = removeDuplicates(a[i], defaults[i], {});
      } else if (a[i] !== defaults[i]) {
        result[i] = a[i];  
      }
    } else {
      result[i] = a[i];
    }
  }

  return result;
}


var result = removeDuplicates(a, defaults, {});

这篇关于从对象中删除默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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