Self referencing an Array of JSON to call a function / to update

I’m currently transitioning from VueJS to AlpineJS and trying to update specific JSON arrays but it doesn’t seem to be updating.

An example:

Any tips or reasonings why this is not working?

var foo = [

          { id: 0, title: 'test', text: c( this ) },
          { id: 1, title: 'test', text: 'text' },
          { id: 2, title: 'test', text: 'text' },

      ]
function c( idk ) {
    console.log( idk.title )
  }


console.log(foo)
var foo = (() => {

  // Paste in your original object
  const foo = [ {
    a: 5,
    b: 6,
  }
  ];
  
  // Use their properties
  foo.c = foo.a + foo.b;

  // Do whatever else you want

  // Finally, return object
  return foo;
})();

  console.log( foo )

These examples were from Self-references in object literals / initializers but has been modified to use an Array of JSON

1 thought on “Self referencing an Array of JSON to call a function / to update”

  1. The first example doesn’t work for exactly the same reason as the question you referenced.

    The second example doesn’t work because foo is the array and not the object inside the array.

    foo.a + foo.b is going to be undefined + undefined which you then assign to foo.c making foo.c Not A Number.

    You then console.log the array and it doesn’t show the c property because it is an array and not designed to have named properties added to it.

    var foo = (() => {
      const foo = [{
        a: 5,
        b: 6,
      }];
    
      console.log(foo.a, foo.b);
    
      foo.c = foo.a + foo.b;
    
      console.log(foo.c);
    
      return foo;
    })();
    
    console.log(foo.c)
    Reply

Leave a Comment