Adding an object to an array of objects with splicing

I have an array of objects that looks like this:

event_id=[{"0":"e1"},{"0","e2"},{"0","e4"}]; 

How to add an element to this array?

I'm thinking of

 event_id.splice(1,0,{"0":"e5"}); 

Thanks.

+9
source share
5 answers

Since I want to add an object to the middle of the array, I finished this solution:

 var add_object = {"0": "e5"}; event_id.splice(n, 0, add_object); // n is declared and is the index where to add the object 
+7
source

If you just want to add a value to the end of the array, then the push(newObj) function is easiest, although splice(...) will also work (a bit more complicated).

 var event_id = [{"0":"e1"}, {"0":"e2"}, {"0":"e4"}]; event_id.push({"0":"e5"}); //event_id.splice(event_id.length, 0, {"0":"e5"}); // Same as above. //event_id[event_id.length] = {"0":"e5"}; // Also the same. event_id; // => [{"0":"e1"}, {"0":"e2"}, {"0":"e4"}, {"0":"e5"}]; 

Refer to the excellent var a = ['a', 'b', 'e']; a.splice( 2, // At index 2 (where the 'e' is), 0, // delete zero elements, 'c', // and insert the element 'c', 'd'); // and the element 'd'. a; // => ['a', 'b', 'c', 'd', 'e'] var a = ['a', 'b', 'e']; a.splice( 2, // At index 2 (where the 'e' is), 0, // delete zero elements, 'c', // and insert the element 'c', 'd'); // and the element 'd'. a; // => ['a', 'b', 'c', 'd', 'e']

+10
source

ES6 solution with distribution operator:

 event_id=[{"0":"e1"},{"0","e2"},{"0","e4"}]; event_id = [...event_id,{"0":"e5"}] 

or if you do not want to modify event_id

 newEventId = [...event_id,{"0":"e5"}] 
+1
source
 event_id.push({"something", "else"}); 

Try using .push(...) ^

0
source

Well, you can usually use:

 event_id[event_id.length] = {"0":"e5"}; 

or (a little slower)

 event_id.push({"0":"e5"}); 

although if you want to insert an element in the middle of the array, and not always at the end, then we will have to come up with something more creative.

Hope this helps,

ISE

0
source

Source: https://habr.com/ru/post/912062/


All Articles