Development Tip

자바 스크립트 개체 속성의 기본값 설정

yourdevel 2020. 11. 16. 22:20
반응형

자바 스크립트 개체 속성의 기본값 설정


다음과 같이 javascript 객체의 기본 속성을 설정하는 방법이 있습니까?

var emptyObj = {};
// do some magic
emptyObj.nonExistingAttribute // => defaultValue

IE는 무시할 수 있습니다. Chrome 프레임은 그 두통을 덜어주었습니다.


몇 년 전에 질문을 한 이후로 상황이 잘 진행되었습니다.

프록시는 ES6의 일부입니다. 다음 예제는 Chrome, Firefox, Safari 및 Edge 에서 작동합니다 .

var handler = {
  get: function(target, name) {
    return target.hasOwnProperty(name) ? target[name] : 42;
  }
};

var p = new Proxy({}, handler);

p.answerToTheUltimateQuestionOfLife; //=> 42

Mozilla의 Proxies 문서에서 더 많은 것을 읽으십시오 .


자바 스크립트에서이를 설정하는 방법은 없습니다. undefined존재하지 않는 속성을 반환 하는 것은 핵심 자바 스크립트 사양의 일부입니다. 이 유사한 질문에 대한 토론을 참조하십시오 . 내가 거기에서 제안했듯이, 한 가지 접근 방식 (정말 추천 할 수는 없지만)은 전역 getProperty함수 를 정의하는 것입니다 .

function getProperty(o, prop) {
    if (o[prop] !== undefined) return o[prop];
    else return "my default";
}

var o = {
    foo: 1
};

getProperty(o, 'foo'); // 1
getProperty(o, 'bar'); // "my default"

그러나 이것은 다른 사람들이 읽기 어려운 비표준 코드로 이어질 수 있으며 정의되지 않은 값을 기대하거나 원하는 영역에서 의도하지 않은 결과를 초래할 수 있습니다. 이동하면서 확인하는 것이 좋습니다.

var someVar = o.someVar || "my default";

사용 destructuring (새 ES6에서)

Mozila의 훌륭한 문서 와 구문을 내가 할 수있는 것보다 더 잘 설명 하는 환상적인 블로그 게시물 이 있습니다.

질문에 답하려면

var emptyObj = {};
const { nonExistingAttribute = defaultValue } = emptyObj;
console.log(nonExistingAttribute); // defaultValue

더 나아 가기

이 변수의 이름을 바꿀 수 있습니까 ? 확실한!

const { nonExistingAttribute: coolerName = 15} = emptyObj;
console.log(coolerName); // 15

중첩 된 데이터는 어떻습니까? 가져와!

var nestedData = {
    name: 'Awesome Programmer',
    languages: [
        {
            name: 'javascript',
            proficiency: 4,
        }
    ],
    country: 'Canada',
};

var {name: realName, languages: [{name: languageName}]} = nestedData ;

console.log(realName); // Awesome Programmer
console.log(languageName); // javascript

이것은 확실히 프로토 타입 기반 개체의 일반적인 사용처럼 들립니다.

// define a new type of object
var foo = function() {};  

// define a default attribute and value that all objects of this type will have
foo.prototype.attribute1 = "defaultValue1";  

// create a new object of my type
var emptyObj = new foo();
console.log(emptyObj.attribute1);       // outputs defaultValue1

내 코드는 다음과 같습니다.

function(s){
    s = {
        top: s.top || 100,    // default value or s.top
        left: s.left || 300,  // default value or s.left
    }
    alert(s.top)
}

또는 이것을 시도 할 수 있습니다

dict = {
 'somekey': 'somevalue'
};

val = dict['anotherkey'] || 'anotherval';

내가 이것을 달성하는 방법은 object.assign기능입니다.

const defaultProperties = { 'foo': 'bar', 'bar': 'foo' };
const overwriteProperties = { 'foo': 'foo' };
const newObj = Object.assign({}, defaultProperties, overwriteProperties);
console.log(defaultProperties);  // {"foo": "bar", "bar": "foo"}
console.log(overwriteProperties);  // { "foo": "foo" };
console.log(newObj);  // { "foo": "foo", "bar": "foo" }

가장 간단한 접근 방식은 Object.assign.

이 클래스가있는 경우 :

class MyHelper {
    constructor(options) {
        this.options = Object.assign({
            name: "John",
            surname: "Doe",
            birthDate: "1980-08-08"
        }, options);
    }
}

You can use it like this:

let helper = new MyHelper({ name: "Mark" });
console.log(helper.options.surname); // this will output "Doe"

Documentation (with polyfill): https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Object/assign


Simplest of all Solutions:

dict = {'first': 1,
        'second': 2,
        'third': 3}

Now,

dict['last'] || 'Excluded'

will return 'Excluded', which is the default value.


I saw an article yesterday that mentions an Object.__noSuchMethod__ property: JavascriptTips I've not had a chance to play around with it, so I don't know about browser support, but maybe you could use that in some way?


I'm surprised nobody has mentioned ternary operator yet.

var emptyObj = {a:'123', b:'234', c:0};
var defaultValue = 'defaultValue';
var attr = 'someNonExistAttribute';
emptyObj.hasOwnProperty(attr) ? emptyObj[attr] : defaultValue;//=> 'defaultValue'


attr = 'c'; // => 'c'
emptyObj.hasOwnProperty(attr) ? emptyObj[attr] : defaultValue; // => 0

In this way, even if the value of 'c' is 0, it will still get the correct value.


This is actually possible to do with Object.create. It will not work for "non defined" properties. But for the ones that has been given a default value.

var defaults = {
    a: 'test1',
    b: 'test2'
};

Then when you create your properties object you do it with Object.create

properties = Object.create(defaults);

Now you will have two object where the first object is empty, but the prototype points to the defaults object. To test:

console.log('Unchanged', properties);
properties.a = 'updated';
console.log('Updated', properties);
console.log('Defaults', Object.getPrototypeOf(properties));

One approach would be to take a defaults object and merge it with the target object. The target object would override values in the defaults object.

jQuery has the .extend() method that does this. jQuery is not needed however as there are vanilla JS implementations such as can be found here:

http://gomakethings.com/vanilla-javascript-version-of-jquery-extend/


Object.withDefault = (defaultValue,o={}) => {
  return new Proxy(o, {
    get: (o, k) => (k in o) ? o[k] : defaultValue 
  });
}

o = Object.withDefault(42);
o.x  //=> 42

o.x = 10
o.x  //=> 10
o.xx //=> 42

This seems to me the most simple and readable way of doing so:

let options = {name:"James"}
const default_options = {name:"John", surname:"Doe"}

options = Object.assign({}, default_options, options)

Object.assign() reference


I came here looking for a solution because the header matched my problem description but it isn't what i was looking for but i got a solution to my problem(I wanted to have a default value for an attribute which would be dynamic something like date).

let Blog = {
title  : String,
image  : String,
body   : String,
created: {type: Date, default: Date.now}
}

The above code was the solution for which i finally settled.

참고URL : https://stackoverflow.com/questions/6600868/set-default-value-of-javascript-object-attributes

반응형