JS: Modify Value/Pair in JS Object

后端 未结 4 1781
一个人的身影
一个人的身影 2021-01-22 17:10

I\'m trying to work out the best way to modify an object without writing out a similar object three times. So I have these three objects:

var object1 = {
    sta         


        
4条回答
  •  感情败类
    2021-01-22 17:53

    If we are dealing with primitives for all of these properties you can use Object.assign with no worries

    var objectTemplate = {
        start: start,
        end: end,
        type: 0
    };
    
    var object1 = Object.assign({}, objectTemplate, {type: 1})
        object2 = Object.assign({}, objectTemplate, {type: 2}),
        object3 = Object.assign({}, objectTemplate, {type: 3});
    

    You don't have to use a template object, you could jump straight into the first object (see previous revision), but as @Blindman67 points out: if you can't guarantee an object will be as you expect then it may be better to use a template which you can guarantee.

提交回复
热议问题