Home > other >  pushing data inside an existing empty array
pushing data inside an existing empty array

Time:07-02

Basically I have an main object dataToMovie, I have empty arrays. I want to display the content of the arr variable into mov[] and the content of the arr2 into ser[]. I have attempted to do something as you can see. I am looking to do this seperately for each array as I will have multiple data in the future

const dataToMovie = {
  createMovie,
  links: {
    mov: [],
    ser: [],
    rev: [],
    ext: [],
  },
};

const dataToInsert1 = {
  'model-10389': 164703,
  'model-10388': 164704,
  'model-10387': 164705,
};

const dataToInsert2 = {
  'model-10389': [1656, 1234, 1245],
  'model-10384': [1656, 1234, 1245],
  'model-10383': [1656, 1234, 1245],
};

const arr = Object.entries(dataToInsert1).map((entry) => ({
  id: entry[0].substring(6, entry[0].length),
  value: entry[1],
}));

//dataToMovie.links.mov[arr]

const arr2 = Object.entries(dataToInsert2).map(([key, value]) => ({
  modelId: key.substring(6),
  ids: value,
}));

//dataToMovie.links.ser[arr2]

CodePudding user response:

concat is a good candidate for this operation. it returns a merged array.

dataToMovie.links.mov = dataToMovie.links.mov.concat( arr )
dataToMovie.links.ser = dataToMovie.links.set.concat( arr2 )

CodePudding user response:

You are close. if the arrays are empty you can just do:

dataToMovie.links.mov = arr
dataToMovie.links.ser= arr2

If the arrays have items in them and you just want to add to them, you can use the spread operator

dataToMovie.links.mov = [...dataToMovie.links.mov, ...arr]
dataToMovie.links.ser = [...dataToMovie.links.ser, ...arr2]
  • Related