使用 JSON 初始化 JavaScript 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5662906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:57:24  来源:igfitidea点击:

Initialize a JavaScript object using JSON

javascriptjson

提问by Dan

I want to do the following

我想做以下事情

var my_json = {
    a : 'lemon',
    b : 1
}

function obj(json){
    this.a = 'apple';
    this.b = 0;
    this.c = 'other default';
}

after assigning

分配后

var instance = obj(my_json)

I want to get

我想得到

instance.a == 'lemon'

回答by ThiefMaster

for(var key in json) {
    if(json.hasOwnProperty(key)) {
        this[key] = json[key];
    }
}

The ifblock is optional if you know for sure that nothing is every going to extend Object.prototype(which is a bad thing anyway).

if如果您确定没有任何东西会扩展Object.prototype(无论如何这是一件坏事),则该块是可选的。

回答by Alex K.

If you want defaults how about;

如果你想要默认值怎么样;

function obj(json){
  var defaults = {
    a: 'apple',
    b: 0,
    c: 'other default'
  }

  for (var k in json)
    if (json.hasOwnProperty(k))
      defaults[k] = json[k];

  return defaults
}