Kevin
Kevin

Reputation: 389

Update an object and combine properties together in javascript?

I am trying to convert an object below:

let obj = {startDate: '2015-08-03', startTime: '12:00AM'}

to

let obj = {startDate: '2015-08-03 12:00AM'}

What is the best way to do that in javascript?

Update

This is what I have currently

export default object => {
 let newObj = {};
Object.keys(object).forEach(item => {
    if (object[item] === '') {
        delete newObj[item];
    } else if (moment.isMoment(object[item])) {
        newObj[item] = object[item].format('YYYY-DD-MM');
    } else if (item === 'startTime') {
        newObj['startDate'] = `${newObj['startDate']} ${object['startTime']}`;
    } else {
        newObj[item] = object[item];
    }
});
return newObj; };

But problem is when I select time field first then the date it will render out as

startDate: "undefined 3:00AM"

What am I missing now?

Thanks for all the help so far.

Upvotes: 0

Views: 98

Answers (3)

keepAlive
keepAlive

Reputation: 6655

You may need to to do that often. If it is so, I would first add a new property-like method; the well known method pop to all Object-instances (via their constructor's prototype). First doing

Object.defineProperty(Object.prototype, 'pop',{
    writable: false
    , configurable: false
    , enumerable: false
    , value: function (name) {
        var value = this[name];
        delete this[name];
        return value;
    }
});

and finally,

obj.startDate += ' ' + obj.pop('startTime')

which makes obj be

{startDate: '2015-08-03 12:00AM'}

Upvotes: 2

Willem van der Veen
Willem van der Veen

Reputation: 36620

You can put it in a new variable

let newDate = obj.startDate + ' ' + obj.startTime

Then put it on your object like this.

let obj.startDate = newDate

Then you can delete the startTime property with:

delete obj.startTime;

Upvotes: 1

Intervalia
Intervalia

Reputation: 10945

If you can use ES6 try this:

let obj = {startDate: '2015-08-03', startTime: '12:00AM'}
obj = {startDate: `${obj.startDate} ${obj.startTime}`}

Upvotes: 2

Related Questions