简体   繁体   中英

How can I add an object into an array using javascript?

I have a array in a app.js file like this:

   var data = [
                {id:1, firstName: 'John', lastName: 'Smith'},
                {id:2, firstName: 'Jane', lastName: 'Smith'},
                {id:3, firstName: 'John', lastName: 'Doe'}
              ];

Right now, I am using Node.js and trying to create a function call addEmployee() in a module.js file. addEmplyee() only takes two argurments, the firstName and lastName of being added. The id value should be calculated as one more than the current maximum id using underscore.js. Here is my code in module.js file, however it doesn't work.

var _ = require('underscore');
module.exports = {
    addEmployee: function (firstName, lastName) {

        function Person(id, firstName, lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.id = function (data) {
                var id = _.max(data, function (data) {
                    return data.id;
                });
                return id.id + 1;
            }
            var person = new Person(id, firstName, lastName);
            data.push(person);
            return data;

        }
    }
}

Is any one can help? Thank you so much in advance!

Try this:

var _ = require('underscore');
module.exports = {
    addEmployee: function (firstName, lastName) {

        function Person(id, firstName, lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.id = (function (data) {
                var id = _.max(data, function (data) {
                    return data.id;
                });
                return id.id + 1;
            })();    //IIFE to invoke function immidiately and thus assign value to id
            data.push({id: this.id,firstName: this.firstName,lastName: this.lastName});
            return data;

        }
    }
}

It should be like this:

var _ = require('underscore');
// import data

module.exports = {
    addEmployee: function (firstName, lastName) {
        // remove id
        function Person(firstName, lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.id = (function (data) {
                var id = _.max(data, function (data) {
                    return data.id;
                });
                return id.id + 1;
            })();    
        }

        // put OUTSIDE - dont need id here
        var person = new Person(firstName, lastName);
        data.push(person);
        return data;
    }
}

First of all you do not call this inner function/contstructor in anyway, thus it's not added to array. Secondly do not define Person inside a function (it'll be defined as new thing on every call - every new Person would be new type). Third thing is that if you'd call your code it'd cause infinite loop (as of calling new on self in constructor will do the same in next new instance and so on). Additionally where do you define/import data?

var _ = require('underscore');

// probably it'd be even better to move this to separate module
function Person(id, firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.id = id;
};

module.exports = {
    addEmployee: function (firstName, lastName) {
        data.push(new Person((_.max(data, function (data) {
            return data.id;
        }) + 1), firstName, lastName));
    }
}

I'd also recommend lodash instead of undescore (drop-in replacement, but better written).


If you need only object keeping the data { id, firstName, lastName } you don't need new type Person :

module.exports = {
    addEmployee: function (firstName, lastName) {
        var id = (_.max(data, function (data) {
            return data.id;
        }) + 1);
        data.push({ id: id, firstName: firstName, lastName: lastName });
    }
}

If you use node 6.X or 4.X+ (not sure if es6 notation works with all 4.X, for sure 4.4+ will do it) with 'use strict'; it could be even shorter:

'use strict';

var _ = require('underscore');

module.exports = {
    addEmployee: function (firstName, lastName) {
        var id = (_.max(data, function (data) {
            return data.id;
        }) + 1);
        data.push({ id, firstName, lastName });
    }
}

And at last, I'd recommend to not mutate data (side effects are bad mostly ) - I'd transform this to something like that (assuming node that can do es6):

'use strict';

const _ = require('underscore');

module.exports = {
    // note that data comes as input
    addEmployee: function (data, firstName, lastName) {
        // obtain next id
        const id = (_.max(data, function (data) {
            return data.id;
        }) + 1);
        // return new data (old data + new object, but without mutation of initial object)
        return [...data, { id, firstName, lastName }];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM