Create multiple fields from one field

Mapping configuration

by Flexmonster Pivot Table

HTML

<script src="https://cdn.flexmonster.com/flexmonster.js"></script>

<div>
  <h2>How to create multiple fields from one field</h2>
  <p>
    For JSON and CSV, you can create multiple fields from one field in the
    <code>dataSource.mapping</code> object. Created fields can be used
    separately in the slice.
  </p>
  <p>
    In this example, we've created <code>Date (hierarchical)</code> and
    <code>Date (string)</code> fields from <code>Date</code> (lines 8-21 in the
    JavaScript box). Use the buttons below to switch between these fields.
  </p>
  <p>
    <a
      href="https://www.flexmonster.com/doc/mapping/#!splitting-fields"
      target="_blank"
    >Visit our docs to learn more about this feature</a>.
  </p>
</div>

<button onclick="setSlice('hierarchical')">Use hierarchical dates</button>
<button onclick="setSlice('string')">Use string dates</button>

<div id="pivot-container"></div>

CSS

@import url(https://cdn.flexmonster.com/assets/jsfiddle-styles.css);

JavaScript

let pivot = new Flexmonster({
  container: "pivot-container",
  componentFolder: "https://cdn.flexmonster.com/",
  report: {
    dataSource: {
      data: getData(),
      mapping: {
      	"Date": [
          {
            type: "date",
            uniqueName: "DateHierarchical",
            caption: "Date (hierarchical)"
          },
          {
            type: "date string",
            uniqueName: "DateString",
            caption: "Date (string)",
            format: "MMMM d, yyyy"
          }
				]
			}
    },
    slice: {
    	rows: [
      	{ uniqueName: "DateString" }
      ],
    	measures: [
      	{ uniqueName: "Price" }
      ]
    }
  }
});

function getData() {
	return [
    {
      "Price": 677,
      "Date": "2019-09-23"
    },
    {
      "Price": 417,
      "Date": "2020-10-20"
    },
    {
      "Price": 800,
      "Date": "2019-09-01"
    },
    {
      "Price": 947,
      "Date": "2020-12-13"
    }
  ];
}

function setSlice(dateType) {
	let slice = {
  	rows: [
    	{ uniqueName: "DateHierarchical.Year" }
    ],
    measures: [
    	{ uniqueName: "Price" }
    ]
  };
  switch (dateType) {
  	case "string":
    	slice.rows[0].uniqueName = "DateString";
      break;
    case "hierarchical":
    	slice.rows.push( { uniqueName: "DateHierarchical.Month" });
      slice.rows.push( { uniqueName: "DateHierarchical.Day" });
    	break;
  }
	pivot.runQuery(slice);
}