简体   繁体   中英

I would like to add data to object without deleting the previous values

Basically I have an object (obj) and I have several if statements to push value into this object. In the first if statement I am creating an object (links) and adding an array (movie) and push the data from the map into it. Then I have a second if where I create another array(serie) after the movie array and push some other data into it. I am repeating this execution twice. My issue now is that I think it is recreating a new array each time which means that the data from the previous if statement is deleteed. How do I achieve this?

 const obj = { projet, file: }; //1 if (....) { const arr1 = Object.entries(....).map((entry) => ({ modelid: entry[0].substring(6, entry[0].length), id: entry[1], })); obj.links.movie = arr1; } //2 if (...) { const arr2 = Object.entries(...).map(([key, value]) => ({ modelId: key.substring(6), ids: value, })); obj.links.serie = arr2; }

this is is the output expected.

 const obj = { projet, file:, links: { movie: [], serie: [], };

First you should check if inside object, under target key(movie or serie), there is some data, if there is then you should just extend it using array spread, and if not then assign initial value to target key(as you did):

 if(obj.links.movie) obj.links.movie.push(...arr1); else eobj.links.movie = arr1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM