如何使用javascript将对象添加到数组中?

时间:2021-10-24 07:34:42

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

我在app.js文件中有一个数组:

   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.

现在,我正在使用Node。并尝试在模块中创建一个函数调用addEmployee()。js文件。addEmplyee()只需要两个参数,第一个名字和最后一个名字。应该将id值作为比当前最大id使用underscore.js的多一个计算。这是我的模块代码。js文件,但不管用。

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!

有人能帮忙吗?非常感谢您!

3 个解决方案

#1


0  

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;

        }
    }
}

#2


0  

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?

首先,你不会调用这个内部函数/contstructor,因此它不会被添加到数组中。其次,不要在一个函数内定义Person(它将被定义为每一个调用中的新事物——每个新用户都是新类型)。第三件事是,如果您调用您的代码,它将导致无限循环(在构造函数中,调用self的新调用将在下一次新实例中执行相同的操作)。另外,您在哪里定义/导入数据?

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).

我也建议用lodash代替undescore (drop-in替代,但写得更好)。


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

如果您只需要保存数据{id、firstName、lastName}的对象,您就不需要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:

如果使用节点6。X或4。X+(不确定es6符号是否适用于所有4)。X,肯定4.4+会做它)用“严格”;它甚至可能更短:

'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):

最后,我建议不要修改数据(主要是副作用)——我将它转换成这样的(假设节点可以做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 }];
    }
}

#3


0  

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;
    }
}

#1


0  

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;

        }
    }
}

#2


0  

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?

首先,你不会调用这个内部函数/contstructor,因此它不会被添加到数组中。其次,不要在一个函数内定义Person(它将被定义为每一个调用中的新事物——每个新用户都是新类型)。第三件事是,如果您调用您的代码,它将导致无限循环(在构造函数中,调用self的新调用将在下一次新实例中执行相同的操作)。另外,您在哪里定义/导入数据?

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).

我也建议用lodash代替undescore (drop-in替代,但写得更好)。


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

如果您只需要保存数据{id、firstName、lastName}的对象,您就不需要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:

如果使用节点6。X或4。X+(不确定es6符号是否适用于所有4)。X,肯定4.4+会做它)用“严格”;它甚至可能更短:

'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):

最后,我建议不要修改数据(主要是副作用)——我将它转换成这样的(假设节点可以做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 }];
    }
}

#3


0  

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;
    }
}