Map over an object and change one properties value using native JS

后端 未结 6 1431
生来不讨喜
生来不讨喜 2021-02-06 22:50

I want to be able to return a result set of data and just change the formatting of the date field to something more readable leaving all the other data intact. I would prefer t

6条回答
  •  深忆病人
    2021-02-06 23:24

    .map() isn't the usual way to modify properties an existing array of objects. You can do that, but it's not what .map() is normally used for. Instead, it's a way to create a new array. A .map() callback returns a value, and those returned values get pushed into a new array, which .map() finally returns.

    Your .map() callback is implicitly returning task.start_date after assigning the formatted date into it. This means you're creating an array of formatted dates only, without the rest of the original task objects. If you wanted to use .map() here it would need to return task after making the assignment to task.start_date.

    But instead you may want to use .forEach() in your .then() callback. This is the method made for this job: it simply iterates over the array and lets you modify each element in place:

    tasks.forEach( task => task.start_date = task.start_date.format("YYYY-MM-DD") );
    return tasks;
    

    Also, as Dustin mentioned, returning a value from .then() may not do what you want here. The safest bet would be to do something with tasks right there, or to call another function and pass tasks as an argument. (I'm a little rusty on promises, though...)

提交回复
热议问题