Skip to content Skip to sidebar Skip to footer

Push Object Into An Array In Javascript

object is not pushing into array. groupEventsArray=[] groupEvents=(eventOnDate)=>{ for(i=0;i

Solution 1:

Consider using forEach() method. The forEach() method calls a provided function once for each element in an array, in order.

Note: forEach() does not execute the function for array elements without values.

Syntax

array.forEach(function(currentValue, index, arr), thisValue)

Example

var numbers = [4, 9, 16, 25];
functionmyFunction(item, index) {
  console.log(item, index);
}

numbers.forEach(myFunction)

Looping over an array like this help avoid infinte loop.

Solution 2:

Sounds like a basic group array by key question. You could do it in the following way:

const data = {
  fullDate: '2018-10-26T09:30:00.000Z',
  events: [
    {
      eventId: '43460',
      start: '1540525500',
    },
    {
      eventId: '43461',
      start: '1540525500',
    },
    {
      eventId: '43462',
      start: '1540525500',
    },
    {
      eventId: '43463',
      start: '1540525510',
    },
  ],
};

constcreateKey = (t) => t.start;
console.log(
  Object.values(
    data.events
      .map((o) => [o, createKey(o)])
      .reduce((result, [item, key]) => {
        result[key] = result[key] || [];
        result[key].push(item);
        return result;
      }, {}),
  ),
);

But the question is probably a duplicate of this one (look for answers not using lodash)

Post a Comment for "Push Object Into An Array In Javascript"