Search code examples
javascriptghost-blog

api is returning an array with numbered and named keys


So I am putting together a NextJS + Ghost CMS decoupled blog and am playing around with the Ghost JS API (specifically the Content API Client Library).

When I run my query using the following...

api.posts
    .browse({ 
      limit: 5,
      page: 1,
      include: 'authors',
      fields: 'excerpt,custom_excerpt,title,id,slug,'
    })  
    .then((posts) => {
      console.log(posts);
        return posts;
      })
    .catch((err) => {
        console.error(err);
    });

... I find that it returning an array. The array had the typical 0 1 2 ... keys. I was surprised to find that it ALSO had a named last item: meta.

See image from chrome JS console.

is this even possible

What is going on here. Did I miss a lesson in JS101 about string-named keys on arrays?


Solution

  • From the MDN:

    Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations.

    In other words, they are a special type of objects. So, like to other objects, you can add named properties to it. However the methods available on his prototype only traverses the numeric-properties. Check next example:

    let arr = [1,2,3,4];
    arr.meta = {foo: "bar"};
    console.log("standard arr display: ", arr);
    console.log("arr.meta: ", arr.meta);
    console.log("Own Property Names: ", Object.getOwnPropertyNames(arr));
    .as-console {background-color:black !important; color:lime;}
    .as-console-wrapper {max-height:100% !important; top:0;}

    Now, I believe that the implementation of the chrome JS console is based on an object prototype method, maybe Object.getOwnPropertNames(), to display all his properties (including the non-enumerable length) and values. You can give a read to Object.defineProperty() to see how to define non-enumerable property using the descriptor argument.