Search code examples
arraysjsonobjectpolymergoogle-cloud-firestore

Polymer dom-repeat and Firestore - convert object map to array


Polymer dom-repeats only accept array data types. I'm using Firestore it's recommended to use object maps rather than array, as these can be queried and updated individually, unlike array elements.

Question is, how do I convert this object map:

{
  "subsections": {
    "0": {
      "title": "my title 1",
      "description": "my desc 1"
    },
    "1": {
      "title": "my title 2",
      "description": "my desc 2"
    }
  }
}

To this array:

{
"subsections": [
  {
    "title": "my title 1",
    "description": "my desc 1"
  },
  {
    "title": "my title 2",
    "description": "my desc 2"
  }
}

Polymer dom-repeat is this:

<template is="dom-repeat" items="{{_toArray(sections.subsections)}}">

Calling:

_toArray(obj) {
  return Object.keys(obj).map(function (key) {
    return {
      name: key,
      value: obj[key]
    };
  });
}

Problem is function returns a nested array of 0 and 1 with title and description nested.

Help! I'm new to all this front end development so any help greatly appreciated.


Solution

  • Change your _toArray function as follows

    _toArray(obj) {
      return Object.keys(obj).map(function (key) {
        return obj[key];
      });
    }
    

    Then call the method as

    obj.subsections = _toArray(obj.subsections);