All Products
Search
Document Center

DataV:Common cases

Last Updated:Apr 17, 2024

This topic describes how to use a data filter by using six examples of how to configure a data source.

Prerequisites

You have reached the Canvas Editor page.

Case 1: data format conversion

  1. In the Canvas Editor pane, add the Graph widget.

  2. Click the Data imageicon in the right-side configuration panel. The Data Settings tab appears.

  3. Click Configure Data Source. The Configure Data Source tab appears.

  4. Modify the static data to the following code:

    { "Clothing": 21, "Food": 29, "Building Materials": 13, "Entertainment": 33 }
    Note

    The chart content becomes blank because the current static data does not match the data format parameter fields.

  5. Select Data Filter and enter the following code in the code editor:

    function objToArr(obj, name, value) {
      const result = [];
      // Loop object data type
      for (const key in obj) {
        const item = {};
        item[name] = key;
        item[value] = obj[key];
        result.push(item);
      }
      return result;
    }
    return objToArr(data, 'name', 'value');
  6. At this time, it is found that the chart is displayed normally.

    Note

    In this case, the data in the object format is converted to the data in the array format. Because the parameter fields are matched again, the chart is displayed normally.

Case 2: Data filtering and sorting

  1. In the Canvas Editor pane, add a line chart widget.

  2. On the Configuration tab of the right-side configuration panel, set Axes > x-axis to Category. image

  3. Click the Data imageicon in the right-side configuration panel. The Data Settings tab appears.

  4. Click Configure Data Source. The Configure Data Source tab appears.

  5. Modify the static data to the following code:

    [
        { "x": "Clothing", "y": 800 }, { "x": "Food", "y": 779 },
        { "x": "Building Materials", "y": 180 }, { "x": "Entertainment", "y": 523 },
        { "x": "Fresh", "y": 192 }
    ]
  6. Select Data Filter and modify the fields based on the following code:

    // Filter
      const result = data.filter(item => {
        return item.y >= 500;
      });
      // Sort the order.
      result.sort((a, b) => a.y - b.y);
      return result;
  7. to view the chart results, the filter sort the categories with y values greater than or equal to 500 in ascending order. image

    Note

    In this example, you can filter and sort objects in an array. You can modify the filter and sort conditions to filter different data and sort the returned data in ascending or descending order.

Case 3: Obtain the current time and format the display

  1. In the Canvas Editor pane, add the Title widget.

  2. Click the Data imageicon in the right-side configuration panel. The Data Settings tab appears.

  3. Click Configure Data Source. The Configure Data Source tab appears.

  4. Select Data Filter and modify the fields based on the following code:

    Gets the current time, formatted as a YYYY-MM-DD HH:mm:ss.

    The return value is returned. Example: 2023-02-17Tue 15:30:00.

    Note
    • Time Format Description:https://momentjs.com/docs/#/displaying/format/

    • Date object description: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

    const getTimeStr = (options = {}) => {
      // Complements the string with zeros. Input: 8, Output: 08
      const strComplement = (str, digit = 2) => {
        str = typeof str !== 'string' ? `${str}` : str;
        const mask = (new Array(digit + 1)).join('0');
        return mask.slice(str.length) + str;
      }
      const { myDate = new Date(), separator = '-' } = options;
      // Obtain the year, month, day, week, hour, minute, and second of the current time.
      const year = myDate.getFullYear();
      const month = strComplement(myDate.getMonth() + 1);
      const date = strComplement(myDate.getDate());
      const day ='Week ${'Day 123456 '.charAt(myDate.getDay())}';
      const hour = strComplement(myDate.getHours());
      const minute = strComplement(myDate.getMinutes());
      const second = strComplement(myDate.getSeconds());
      const timeStr = `${year}${separator}${month}${separator}${date} ${day} ${hour}:${minute}:${second}`;
      return timeStr;
    }
    // [Try] Change '-' to '/' to see what happens.
    return [{ value: getTimeStr({separator: '-'}) }];                 
    Note
    • In this example, the method is implemented to obtain the current time. The return value is in the format of Tue, 2023-02-07, 17:37:55.

    • You can use the delimiter, such as getTimeStr({separator: '/'}). The return value is in the format of 2023/02/07 Tue 17:37:55.

    • You can modify the timeStr field to customize the display of the combined year, month, day, hour, minute, and second. For example, you can change the value to timeStr = '${year}${separator}${month}${separator}${date}'. The format of the return value is 2023-02-07.

Case 4: Configure hyperlink redirection

  1. In the Canvas Editor pane, add the carousel list component.

  2. Click the Data imageicon in the right-side configuration panel. The Data Settings tab appears.

  3. Click Configure Data Source. The Configure Data Source tab appears.

  4. Modify the static data to the following code:

    [{ "area": "Zhejiang", "attribute": "100" }, { "area": "Jiangsu", "attribute": "200" }]
  5. Select Data Filter and modify the fields based on the following code:

    // Obtain the hyperlink label.
    const getLinkTag = (baseURL = '', param = {}, style = {}) => {
        const joint = (obj, insideSeparator = '', betweenSeperator = '') => {
            const result = [];
            for (const key in obj) {
                result.push(`${key}${insideSeparator}${obj[key]}`);
            }
            return result.join(betweenSeperator);
        }
        const url = `${baseURL}?${joint(param, '=', '&')}`;
        const styleCss = joint(style, ':', ';');
        return [
            `<a href="${url}" target="_blank" style="${styleCss}" >`,
            '</a>'
        ]
    }
    return data.map(item => {
        // [Try] Change the https://www.aliyun.com to https://datav.aliyun.com to see the effect
        const baseURL = 'https://www.aliyun.com';
        // [Try] Change area: item.area to id: item.area to see the effect
        const param = {
            area: item.area,
        };
        // [Try] Change color: 'blue' to color: 'red' to see the effect
        const style = {
            color: 'blue',
            background: 'yellow'
        }
        // Set the hyperlink.
        return {
            ...item,
            attribute: getLinkTag(baseURL, param, style).join(item.attribute),
        }
    });
    Note

    This case implements the method of obtaining the hyperlink label, the baseURL parameter is the address to be jumped, the param is the parameter spliced on the hyperlink, and the style parameter is the style attribute of the hyperlink label.

Case 5: Rounding, keep n decimal places

  1. In the Canvas Editor pane, add the carousel list component.

  2. Click the Data imageicon in the right-side configuration panel. The Data Settings tab appears.

  3. Click Configure Data Source. The Configure Data Source tab appears.

  4. Modify the static data to the following code:

    [{ "y": 1 }, { "y": 1.2246 }, { "y": 1.2332 }]
  5. Select Data Filter and modify the fields based on the following code:

     const toFixDecimal = (num, ...args) => {
         const digit = typeof args[0] === 'number' ? args[0] : 2;
         const options = typeof args[0] === 'object' ? args[0] : (args[1] || {});
         const { keepInt = true } = options;
         const value = Number.parseFloat(num);
         if (keepInt) {
             const base = Math.pow(10, digit);
             return Math.round(value * base) / base;
         } else {
             return value.toFixed(digit);
         }
     }
     // Loop list data type
     const result = data.map((item) => {
         // [Try] Open the following comments separately to see the effect
         const newValue = toFixDecimal(item.y); // [ { y: 1 }, { y: 1.22 }, { y: 1.23 } ]
         // const newValue = toFixDecimal(item.y, 1); // [ { y: 1 }, { y: 1.2 }, { y: 1.2 } ]
         // const newValue = toFixDecimal(item.y, {keepInt: false}); // [ { y: '1.00' }, { y: '1.22' }, { y: '1.23' } ]
         // const newValue = toFixDecimal(item.y, 1, {keepInt: false}); // [ { y: '1.0' }, { y: '1.2' }, { y: '1.2' } ]
         return {
             ...item,
             y: newValue
         }
     });
     return result;                     
    Note
    • In this example, the method is implemented to retain the specified number of decimal places. The first parameter is the data field that needs to be retained for decimal processing. By default, two decimal places are retained. However, you can specify the number of decimal places. For example, newValue = toFixDecimal(item.y,3) three decimal places are retained, the sample data will be returned: [{ y: 1 }, { y: 1.225 }, { y: 1.233 }].

    • If the data format you want to display is '1.00', you must specify {keepInt: false}. If you specify newValue = toFixDecimal(item.y, 3, {keepInt: false}), the data in the string format is [{ y: '1.000' }, { y: '1.225' }, { y: '1.233' }].

Case 6: Complex array deduplication

  1. In the Canvas Editor pane, add the carousel list component.

  2. Click the Data imageicon in the right-side configuration panel. The Data Settings tab appears.

  3. Click Configure Data Source. The Configure Data Source tab appears.

  4. Modify the static data to the following code:

    [
        { "x": "Clothing", "y": 800 }, { "x": "Food", "y": 779 },
        { "x": "Building materials", "y": 180 }, { "x": "Food", "y": 779 },
        { "x": "Clothing", "y": 192 }
    ]
  5. Select Data Filter and modify the fields based on the following code:

    function uniq(arr, keyList) {
        const valueSet = {};
        return arr.reduce((result, item) => {
            const key = keyList.map((k) => item[k]).join('#@#');
            if (!valueSet[key]) {
                result.push(item);
                valueSet[key] = true;
            }
            return result;
        }, []);
    }
    // [Try] Open the following comments in turn to see the effect. x and y are object keys.
    return uniq(data, ['y']);
    // return uniq(data, ['x']);
    // return uniq(data, ['x', 'y']);                    
    Note

    In this case, array deduplication is implemented. You can return deduplication data by passing a specified field, as shown in the example data according to y field deduplication, uniq(data, ['y']), the returned data is [{ "x": "clothing", "y": 800 }, { "x": "food", "y": 779 }, { "x": "building materials", "y": 180 },{ "x": "clothing", "y": 192 }], y data with the same field value will only be retained in the first order; x and y field deduplication, uniq(data, ['x', 'y']), then x and y data with the same field value is retained first in sequence.