I am trying to transform an array into a slightly different format, and am using the splice for now like below:
letnewArray.splice( idx , 0 , obj );
My entire code can be seen below:
let yaml_doc_json = [{ name: 'guidIds', ids: ['209A3935-2305-4786-960B-BB008F3E9DC9', 'C10D76D2-89A3-4F28-B64E-2D78C953B283', 'B7164432-94B3-4096-A9EA-181D0F00D25E', 'DA366048-557F-42ED-AB1D-3B2196278E86' ] }, { name: 'keyMessage', ids: ['Enbril_RA_30.00', 'Enbril_RA_40.00', 'Enbril_RA_50.00', 'Enbril_RA_10.00' ] }, { name: 'SequenceName', ids: ['1_KEY_LUN_09_2017_Ukr_main', '1_KEY_LUN_09_2017_Ukr_sl01', '1_KEY_LUN_09_2017_Ukr_sl02', '1_KEY_LUN_09_2017_Ukr_sl03' ] } ], letnewArray = []; yaml_doc_json.forEach((e, i) => { //console.log(e); let id_name = yaml_doc_json[i].name; //console.log(id_name); e['ids'].forEach((elem, idx) => { console.log(idx); let obj = { id_name: elem } letnewArray.splice(idx, 0, obj); }); }); console.log(letnewArray);
How come i get 12 elements in letnewArray
even though idx
is always between 0-3 ? should't the elements at the specific index be overridden everytime the forEach loop runs ? why is the overriding now happening ? what am i really doing wrong here ?
The 12 elements in the letnewArray
come from having each of the three elements in yaml_doc_json
elaborated four times (the number of ids
elements).
The fact that there are 12 is because of the syntax of Array.prototype.splice
. The complete reference can be found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
The important part is the syntax: array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
Let us turn back to your code. We have letnewArray.splice( idx , 0 , obj );
Going by the definition above, we can infer
array => letnewArray
start => idx
deleteCount => 0
item1 => obj
The various item1, item2, ...
elements are added to the array. Therefore, each time the for loop cycles through, we delete 0 items and add 1 element.
This shows why the ending elements in the letnewArray
variable are 12.
I hope to have been useful.
Splice will add the third argument to existing array. Refer https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_splice1
@charlietfl answered this in the comments !.
The second argument of splice() is the deleteCount. If it is zero then all you do is insert the new item and all others at that index and beyond will shift to the right.
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.