How can I add objects into an array without using push method in Javascript?

I am trying to add object into an array.

Here is the code.

const output = { 201911: {15: {...}}, 201912: {10:{...}} } 
const keys = Object.keys(output) // ['201911', 201912']

let arr = []

keys.map((item, index) => arr.push({[keys[index]]: output[item]})) // [ {201911:{...}, {201912:{...}]

I can easily add objects into an array using push method but I am afraid this might causing an issue in a future and also I do not want to mutate array directly using push, shift or unshift methods etc...

Is there a safer way to add objects into an array?

2 answers

  • answered 2019-12-15 03:24 Pointy

    All you need to do is use the .map() function the way it was intended:

    const output = { 201911: {15: {...}}, 201912: {10:{...}} };
    const keys = Object.keys(output);
    
    let arr = keys.map((item, index) => 
      ({[keys[index]]: output[item]})
    );
    

    The .map() function is used when you want to apply a function to each element of a source array and use the returned value as an element of a new array. Because the whole point of .map() is to make a new array from the elements of an existing array, there's no need for your code to manipulate the new array at all.

    There's nothing wrong with .push() otherwise; your concerns are unfounded.

  • answered 2019-12-15 03:28 Olian04

    I do not want to mutate array directly using push, shift or unshift methods etc...

    You could destructure the array into a new array that contains the added element as well.

    const output = { 201911: {15: {}}, 201912: {10:{}} } 
    const keys = Object.keys(output);
    
    let arr = [];
    
    console.log(arr);
    
    arr = keys.reduce((res, item, index) =>  [...res, {[keys[index]]: output[item]}], arr);
    
    console.log(arr);