Преобразовать десятичное число в процент в javascript - PullRequest
0 голосов
/ 22 января 2020

Я сделал код для возврата json, пример ниже:

[
  {
    "id": "12345",
    "header": "<a class=\"card-link\" href=\"http://www.google.com\" target=\"_blank\"> 12345</a>- solved-1",
    "title": "Training Summary Report",
    "description": "",
    "link": "",
    "labels": [
      {
        "filter": "type",
        "value": "course 1"
      },
      {
        "filter": "Subject",
        "value": "Sub. 1239"
      },
      {
        "filter": "Idea",
        "value": "Idea . 53"
      }
    ]
  }

    {
    "id": "12345",
    "header": "<a class=\"card-link\" href=\"http://www.google.com\" target=\"_blank\"> 12345</a>- solved-1",
    "title": "Training Summary Report",
    "description": "",
    "link": "",
    "labels": [
      {
        "filter": "type",
        "value": "course 1"
      },
      {
        "filter": "Subject",
        "value": "Sub. 1239"
      },
      {
        "filter": "Idea",
        "value": "Idea . 53-34-98:0.0045, 98-11-00:0.09856, 44-22-88:0.09875, 22-98-90:0.3245"
      }
    ]
  }
]

Эти json, что я имею в результате. Я хотел бы изменить десятичные числа в значении Idea в процентах:

53-34-98:0.0045, 98-11-00:0.09856, 44-22-88:0.09875, 22-98-90:0.3245

Expect result:

53-34-98:0,45%, 98-11-00:9.8%, 44-22-88:9.875%, 22-98-90:32%

Таким образом, результатом будет:

{
    "id": "12345",
    "header": "<a class=\"card-link\" href=\"http://www.google.com\" target=\"_blank\"> 12345</a>- solved-1",
    "title": "Training Summary Report",
    "description": "",
    "link": "",
    "labels": [
      {
        "filter": "type",
        "value": "course 1"
      },
      {
        "filter": "Subject",
        "value": "Sub. 1239"
      },
      {
        "filter": "Idea",
        "value": "Idea . 53-34-98:0,45%, 98-11-00:9.8%, 44-22-88:9.875%, 22-98-90:32%"
      }
    ]
  }

Мой код следующий:

result = ""
            if(queryResult.final_Matrix[index] == null){
                if(queryResult.idea[index] != null){
                    result = "Idea. " + queryResult.idea[index]
                }
            }
            else{
                result = "Idea. " + queryResult.final_Matrix[index]  // the result of this line is: "value": "Idea . 53-34-98:0,45%, 98-11-00:9.8%, 44-22-88:9.875%, 22-98-90:32%"
            }

Пример набора данных столбца final_Matrix:

53-34-98:0.0045, 98-11-00:0.09856, 44-22-88:0.09875, 22-98-90:0.3245

Кто-нибудь может помочь мне изменить код, чтобы преобразовать десятичное число в процент? Спасибо

Ответы [ 4 ]

1 голос
/ 22 января 2020

Вы можете сначала разделить строку, содержащую ваши данные (queryResult.final_Matrix[index]), чтобы раздельно получить каждую часть, затем для каждой части снова разделить, используя ":", и примените некоторую математику (умножьте на 100), чтобы получить процент:

let input = "53-34-98:0.0045, 98-11-00:0.09856, 44-22-88:0.09875, 22-98-90:0.3245";

let times = input.split(", ");

const result = [];

times.forEach((elem) => 
{
  const tempArr = elem.split(":");
  result.push(tempArr[0] + ":" + (Math.round((tempArr[1] * 100) * 100) / 100) + "%");
});

let finalResult = result.join(", ");

console.log(finalResult);
0 голосов
/ 22 января 2020

1) l oop к вашим необработанным данным
2) по ключу 'label', найдите массив с помощью 'filter' === 'Idea'
3) выполните разбиение и объединитесь, чтобы преобразовать

data=[{...'label':{'filter':'Idea'...}...},{}];

var labels=[],valueInd=[],value=[],div2=[];
data.map((element)=>{
  labels = element.labels;
  valueInd=labels.findIndex(elem=>elem.filter==='Idea');
  value=labels[valueInd].value;
  value=value.split(' . ')[0]+ ' . '+value.split(' . ')[1].split(',').map((elem)=>{
          var div2=elem.split(':');
         return div2.length>1?div2[0]+':'+(Number(div2[1])*100).toFixed(2)+'%':div2[0];
  }).join(',');
  labels[valueInd].value=value;
});

console.log(data);

Демо

0 голосов
/ 22 января 2020

Вот преобразование объекта с использованием строковых split, join методов.

const convert = item => {
  const labels = item.labels.map(label => {
    if (label.value.includes("Idea")) {
      return {
        ...label,
        value: label.value
          .split(",")
          .map(val => {
            const strs = val.split(":");
            const last = strs.pop();
            strs.push(`${Math.round(Number(last) * 100 * 100) / 100}%`);
            return strs.join(":");
          })
          .join(",")
      };
    } else {
      return { ...label };
    }
  });
  return {
    ...item,
    labels
  };
};

const arr = [
  {
    id: "12345",
    header:
      '<a class="card-link" href="http://www.google.com" target="_blank"> 12345</a>- solved-1',
    title: "Training Summary Report",
    description: "",
    link: "",
    labels: [
      {
        filter: "type",
        value: "course 1"
      },
      {
        filter: "Subject",
        value: "Sub. 1239"
      },
      {
        filter: "Idea",
        value: "Idea . 53"
      }
    ]
  },
  {
    id: "12345",
    header:
      '<a class="card-link" href="http://www.google.com" target="_blank"> 12345</a>- solved-1',
    title: "Training Summary Report",
    description: "",
    link: "",
    labels: [
      {
        filter: "type",
        value: "course 1"
      },
      {
        filter: "Subject",
        value: "Sub. 1239"
      },
      {
        filter: "Idea",
        value:
          "Idea . 53-34-98:0.0045, 98-11-00:0.09856, 44-22-88:0.09875, 22-98-90:0.3245"
      }
    ]
  }
];

console.log(arr.map(convert));
0 голосов
/ 22 января 2020

Вы можете l oop, разделить по строкам, уменьшив массив токенов (разделенных запятой ,) и, наконец, перестроить токены с преобразованными процентными значениями.

let arr = [  {    "id": "12345",    "header": "<a class=\"card-link\" href=\"http://www.google.com\" target=\"_blank\"> 12345</a>- solved-1",    "title": "Training Summary Report",    "description": "",    "link": "",    "labels": [      {        "filter": "type",        "value": "course 1"      },      {        "filter": "Subject",        "value": "Sub. 1239"      },      {        "filter": "Idea",        "value": "Idea . 53"      }    ]  },    {    "id": "12345",    "header": "<a class=\"card-link\" href=\"http://www.google.com\" target=\"_blank\"> 12345</a>- solved-1",    "title": "Training Summary Report",    "description": "",    "link": "",    "labels": [      {        "filter": "type",        "value": "course 1"      },      {        "filter": "Subject",        "value": "Sub. 1239"      },      {        "filter": "Idea",        "value": "Idea . 53-34-98:0.0045, 98-11-00:0.09856, 44-22-88:0.09875, 22-98-90:0.3245"      }    ]  }];

arr.forEach(({labels}) => {
  labels.forEach(label => {
    let [_, value] = label.value.split("Idea . ");
    if (value) {
      label.value = "Idea . " + value.split(",").reduce((a, t) => {
        let [str, perc] = t.split(":");
        if (perc) str += ":" + (Number(perc.trim()) * 100).toFixed(2) + "%"
        return a.concat(str);
      }, []).join();
    }
  });
});

console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }
...