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

后端 未结 6 1430
生来不讨喜
生来不讨喜 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:20

    you can make a generic function which take array of objects and return array with modified-props objects using map() and Object.assign().

    const users = [
        { name: 'Jhon', logged: 'Tue Feb 04 2020 14:16:10 GMT+0200 (Eastern European Standard Time)'  },
        { name: 'Doe', logged: 'Tue Feb 04 2020 14:20:10 GMT+0200 (Eastern European Standard Time)'  }
    ];
    
    
    const handleDates = (list, prop) => {
        return list.map(item => {
          const obj = Object.assign({}, item);
          obj[prop] = new Date(obj[prop]).toLocaleDateString();
          return obj;
        });
    }
    
    console.log(users)
    console.log(handleDates(users, 'logged'))

提交回复
热议问题