What is the equivalent of the spread operator (...) for object properties?

I am creating a note taking application and require that I pass the time that the user takes into the constructor function that stores it. Here is the destination:

var NoteTime = function(minute, hour, day, month, year) {
    var d = new Date();
    this.millisec = d.getMilliseconds();
    this.minute = minute || d.getMinutes();
    this.hour = hour || d.getHours();
    this.day = day || d.getDay();
    this.month = month || d.getMonth();
    this.year = year || d.getUTCFullYear();
}

var gatheredTime = {
    minute: null,
    hour: null,
    day: null,
    month: null,
    year: null
}

I know I can get through gatheredTimelike this

var storeResult = new NoteTime(gatheredTime[prop1], gatheredTime[prop2]....etc)

But I would like to use less code and pass the value as if I were an array:

var storeResult = new NoteTime(...gatheredTime)

Yes, I can convert it to an array, but I would like to know if there is a better way.

+4
source share
2 answers

Use Destruction Assignment

var NoteTime = function (gatheredTime) {
    let {minute, hour, day, month, year} = gatheredTime;

var NoteTime = function(gatheredTime) {
  let {
    minute, hour, day, month, year
  } = gatheredTime;
  console.log(minute, hour, day, month, year);
  // code here
};

var gatheredTime = {
  minute: 10,
  hour: 5,
  day: 9,
  month: 8,
  year: 2016
};

NoteTime(gatheredTime);
Run codeHide result

Alternatively, parameters can be directly destroyed in the arguments.

var NoteTime = function ({minute, hour, day, month, year}) {
+4
source

, , [Symbol.iterator], t21 > loop spread JS. :

var o = {a:1,b:2,c:3},
    a = [];
o[Symbol.iterator] = function*(){
                       var ok = Object.keys(this),
                            i = 0;
                       while (i < ok.length) yield this[ok[i++]];
                     };
for (var value of o) console.log(value);
// or you can even do like
a = [...o];
console.log(a);
Hide result

, .

0

Source: https://habr.com/ru/post/1650647/


All Articles