Deleting or moving an object from an array of objects

Using Sugarcube 2.30

<<set $objArray1 to { “test1”: { somekey: 1 }, “test2”: { somekey: 1} }>>
<<set $objArray2 to { “test3”: { somekey: 3} }>>

I understand I can use jQuery.extend to add objArray2 to objArray1

All works well.

How do I remove/delete a specific object like “test2”? Better yet, how do I move “test2” object into another object array like objArray3?

Object arrays aren’t really arrays. They’re just an object with a bunch of members. You can index over an objects members like an array, but it’s not really one.

For example:

// this object
var bleh = new function() {
    this.a = 1;
    this.b = 2;
};

// is the same as
var bleh = {a: 1, b: 2};

That having been said, it’s actually a lot easier to delete items and move items from an object than an array.

// initialize 
var test1 = {a: 1, b: 1};
var test2 = {};

// copy
test2.a = test1.a;
// another way of writing it
test2["a"] = test1["a"];

// delete
delete test1.a;
// or
delete test1["a"];

Edit: Revised answer to use delete operator.

Wow. That worked just as I needed. Thank you!

I had a brainfart and forgot that delete existed. Both methods work, but setting it to undefined will leave the member but with a value of undefined.

Two takeaways from this is that in both instances if (test1.a === undefined) will return true. Also, I believe the item will not be saved to local storage in both cases. Undefined items get removed when converting to JSON.

However, an example of the differences:

var test = {a: 1, b: 2};

test.a = undefined; // test = {a: undefined, b: 2}
delete test.a; // test = {b: 2};

Hopefully that all makes sense.

@sirslice

The TwineScript equivalent of the above JavaScript code would look like…

<<run delete test1.a >>
or
<<run delete test1["a"] >>

note: You could also use the <<set>> macro in place of the above <<run>> macro calls, because the two macros are functionally identical. I use the <<run>> macro because I feel it reads better when doing actions like this.

1 Like

Just got back on to ask that very question. Thanks!

If it helps, you might also want to check out the “Arrays vs Generic Objects” section of the UInv help file. It goes over different ways of working with the two.