Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add items to array in nodejs

How do I iterate through an existing array and add the items to a new array.

var array = [];
forEach( calendars, function (item, index) {
    array[] = item.id
}, done );

function done(){
   console.log(array);
}

The above code would normally work in JS, not sure about the alternative in node js. I tried .push and .splice but neither worked.

like image 955
Ben Scarberry Avatar asked Sep 29 '13 23:09

Ben Scarberry


2 Answers

Check out Javascript's Array API for details on the exact syntax for Array methods. Modifying your code to use the correct syntax would be:

var array = [];
calendars.forEach(function(item) {
    array.push(item.id);
});

console.log(array);

You can also use the map() method to generate an Array filled with the results of calling the specified function on each element. Something like:

var array = calendars.map(function(item) {
    return item.id;
});

console.log(array);

And, since ECMAScript 2015 has been released, you may start seeing examples using let or const instead of var and the => syntax for creating functions. The following is equivalent to the previous example (except it may not be supported in older node versions):

let array = calendars.map(item => item.id);
console.log(array);
like image 104
nkron Avatar answered Oct 21 '22 07:10

nkron


Here is example which can give you some hints to iterate through existing array and add items to new array. I use UnderscoreJS Module to use as my utility file.

You can download from (https://npmjs.org/package/underscore)

$ npm install underscore

Here is small snippet to demonstrate how you can do it.

var _ = require("underscore");
var calendars = [1, "String", {}, 1.1, true],
    newArray = [];

_.each(calendars, function (item, index) {
    newArray.push(item);
});

console.log(newArray);
like image 10
Gaurang Jadia Avatar answered Oct 21 '22 05:10

Gaurang Jadia