0

If given an object as a parameter to modify a created ExcelFile (using Class), how can I go through that object to find what parameter needs to be modified and then changed in the ExcelFile?

For example if I call modify({date: 12/31/2020}) I want it to update the date to 12/31/2020, however if I give it modify({date: '12/31/2020', duration: '60 minutes'}) it would update both date and duration.

My thinking was below but it is not identifying date...

class ExcelFile{
    constructor(arr){
        this.date = arr[0];
        this.duration = arr[1];
    }
    modify(obj){
        for (let key in obj) {
            if (obj[key] === "date") {
                 this.date = obj[date];
            }
        }
    }
}
vsync
  • 118,978
  • 58
  • 307
  • 400

2 Answers2

0

You are on the right track, just change the properties directly using this[key]:

class ExcelFile{
    constructor(arr){
        this.date = arr[0];
        this.duration = arr[1];
    }
    modify(obj){
        for (let key in obj) {
            this[key] = obj[key]
        }
    }
}

let file = new ExcelFile(["01/01/2020", "30 minutes"])
console.log(file)

file.modify({ date: "02/02/2020" })
console.log(file)

file.modify({ date: '12/31/2020', duration: '60 minutes' })
console.log(file)

// You can also add new properties:
file.modify({ date: '12/01/2005', size: "100 Mb" })
console.log(file)
Anurag Srivastava
  • 14,077
  • 4
  • 33
  • 43
0

If you only need to modify the date property of your ExcelFile instance then you do not need to iterate the Object you are sending to the modify method, but you can directly access the date property of the argument via destructuring

class ExcelFile{
    constructor(arr){
        this.date = arr[0];
        this.duration = arr[1];
    }
    modify({date, duration}){
        this.date = date || this.date
        this.duration = duration || this.duration
    }
}

const file = new ExcelFile(["01/01/2020", "30 minutes"])
console.log(file)

file.modify({ date:"NEW DATE! 10/10/3000" })
console.log(file)

file.modify({ date:"foo", duration:"bar", unwanted:"baz" })
console.log(file)
vsync
  • 118,978
  • 58
  • 307
  • 400