Добавить недостающие ключи, значения и данные в объект json - PullRequest
1 голос
/ 20 октября 2019

У меня есть большой кусок данных JSON, которые динамически изменяются, но. Каждый объект JSON имеет дату, site_nm и другие значения. Даты не совпадают для всех. Отдельные даты в этом наборе данных: 2019-10-01,2019-10-02,2019-10-03,2019-10-04,2019-10-05 . Например, в этом наборе данных это один объект, имеющий: {"site_nm": "GB", "date": "2019-10-01", "sigh": 1, "yo": 1, "wokay": 1} и {"site_nm": "GB", "date": "2019-10-03", "sigh": 3, "yo": 1, "wokay": 0}, но не значение 2019-10-03,2019-10-04,2019-10-05 . В любом случае можно добавить отсутствующие даты для каждого из сайтов и сделать значения для sigh, yo и wokay равными нулю?

Например, для сайта: GB и даты: 2019-10-01, 2019-10-02,2019-10-03,2019-10-04,2019-10-05

Можно ли заполнить набор данных для каждого сайта, чтобы он выглядел примерно так:

  • {"site_nm": "GB", "date": "2019-10-01", "sigh": 1, "yo": 1, "wokay": 1}
  • {"site_nm": "GB", "date": "2019-10-02", "sigh": '', "yo": '', "wokay": ''}
  • {"site_nm ":" GB "," date ":" 2019-10-03 "," sigh ": 3," yo ": 1," wokay ": 0}
  • {" site_nm ":" GB"," date ":" 2019-10-04 "," sigh ": ''," yo ": ''," wokay ": ''}
  • {" site_nm ":" GB ","date": "2019-10-05", "sigh": '', "yo": '', "wokay": ''}

Я могу разделить значения на основеНа сайте имя usinf уменьшить. Но как я могу добавить недостающие значения?

const comp = (key, order = 'asc') => {
  return function(a, b) {
    if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
      return 0;
    }

    const varA = (typeof a[key] === 'string') ?
      a[key].toUpperCase() : a[key];
    const varB = (typeof b[key] === 'string') ?
      b[key].toUpperCase() : b[key];

    let comparison = 0;
    if (varA > varB) {
      comparison = 1;
    } else if (varA < varB) {
      comparison = -1;
    }
    return (
      (order === 'desc') ? (comparison * -1) : comparison
    );
  };
}

const convert_date = function(d) {
  return moment(d.date, 'YYYY-MM-DD').unix() * 1000;
};

let json = [{"site_nm": "gs Universe", "date": "2019-10-01", "sigh": 1, "yo": 1, "wokay": 0}, {"site_nm": "gs GP", "date": "2019-10-01", "sigh": 4, "yo": 3, "wokay": 2}, {"site_nm": "gs Universe Trailers", "date": "2019-10-01", "sigh": 5, "yo": 5, "wokay": 0}, {"site_nm": "TR", "date": "2019-10-01", "sigh": 4, "yo": 4, "wokay": 0}, {"site_nm": "gs", "date": "2019-10-01", "sigh": 5, "yo": 5, "wokay": 2}, {"site_nm": "GB", "date": "2019-10-01", "sigh": 1, "yo": 1, "wokay": 1}, {"site_nm": "cn", "date": "2019-10-01", "sigh": 4, "yo": 4, "wokay": 1}, {"site_nm": "RS", "date": "2019-10-01", "sigh": 1, "yo": 1, "wokay": 0}, {"site_nm": "TV", "date": "2019-10-01", "sigh": 1, "yo": 1, "wokay": 0}, {"site_nm": "ZD", "date": "2019-10-01", "sigh": 2, "yo": 2, "wokay": 0}, {"site_nm": "Car", "date": "2019-10-01", "sigh": 1, "yo": 1, "wokay": 0}, {"site_nm": "gs Trailers", "date": "2019-10-01", "sigh": 3, "yo": 3, "wokay": 0}, {"site_nm": "gs News", "date": "2019-10-01", "sigh": 3, "yo": 3, "wokay": 0}, {"site_nm": "gs Mobile", "date": "2019-10-01", "sigh": 1, "yo": 1, "wokay": 0}, {"site_nm": "gs Universe Trailers", "date": "2019-10-02", "sigh": 1, "yo": 1, "wokay": 0}, {"site_nm": "gs GP", "date": "2019-10-04", "sigh": 6, "yo": 6, "wokay": 2}, {"site_nm": "RS", "date": "2019-10-02", "sigh": 2, "yo": 2, "wokay": 0}, {"site_nm": "gs", "date": "2019-10-02", "sigh": 3, "yo": 3, "wokay": 2}, {"site_nm": "TR", "date": "2019-10-02", "sigh": 4, "yo": 3, "wokay": 0}, {"site_nm": "cn Highlights", "date": "2019-10-03", "sigh": 8, "yo": 8, "wokay": 0}, {"site_nm": "gs Universe", "date": "2019-10-02", "sigh": 1, "yo": 1, "wokay": 0}, {"site_nm": "cn en Espa\u00f1ol", "date": "2019-10-02", "sigh": 6, "yo": 6, "wokay": 0}, {"site_nm": "gs Trailers", "date": "2019-10-02", "sigh": 2, "yo": 2, "wokay": 0}, {"site_nm": "ZD", "date": "2019-10-02", "sigh": 4, "yo": 4, "wokay": 1}, {"site_nm": "cn", "date": "2019-10-05", "sigh": 5, "yo": 5, "wokay": 1}, {"site_nm": "TV", "date": "2019-10-02", "sigh": 1, "yo": 1, "wokay": 0}, {"site_nm": "CH", "date": "2019-10-02", "sigh": 1, "yo": 1, "wokay": 0}, {"site_nm": "GB", "date": "2019-10-02", "sigh": 3, "yo": 3, "wokay": 3}, {"site_nm": "DLNow", "date": "2019-10-02", "sigh": 1, "yo": 0, "wokay": 0}, {"site_nm": "gs News", "date": "2019-10-02", "sigh": 2, "yo": 2, "wokay": 0}]

   let sites = [...new Set(json.map(({
        site_nm
      }) => site_nm))].sort();
      let dates = [...new Set(json.map(({
        date
      }) => date))].sort();
//      console.log(dates);
//      console.log(sites);
      $('#sites').text(sites);
      $('#dates').text(dates);

 
    series = sites.reduce((a, c, i) => {
    console.log(a);
      cur_data = json.filter(d => {
        return d.site_nm === c
      }).sort(comp('date'));

      return [...a, {
        name: c.replace(/_/g, ' '),
        data: cur_data.reduce((aa, cc) => {
          return [...aa, {
            x: +convert_date(cc),
            y: +cc.sigh,
            yo: +cc.yo, wokay: +cc.wokay
          }];
        }, [])
      }];
    }, []);
    

  
    
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

<p id='sites'></p>
<p id='dates'></p>
<div id="stuff"></div>

1 Ответ

0 голосов
/ 20 октября 2019

Просто извлеките все даты, выполните итерацию от самой низкой к самой высокой и проверьте, существует ли она

for (var date = moment("2019-10-01", "YYYY-MM-DD"); date <= moment("2019-10-05", "YYYY-MM-DD"); date = date.add(1, 'days'))
    console.log(date.format("YYYY-MM-DD"));

var data = [
  {"site_nm": "GB", "date": "2019-10-01", "sigh": 1, "yo": 1, "wokay": 1},
  {"site_nm": "GB", "date": "2019-10-03", "sigh": 3, "yo": 1, "wokay": 0}
];

var existingDates = new Set(data.map(x => x.date));

for (
  var date = moment("2019-10-01", "YYYY-MM-DD"); 
  date <= moment("2019-10-05", "YYYY-MM-DD");
  date = date.add(1, 'days')) {
    var dateFormatted = date.format("YYYY-MM-DD");
    if (!existingDates.has(dateFormatted)) {
      data.push({"site_nm": "GB", "date": dateFormatted, "sigh": "", "yo": "", "wokay": ""});
    }
}

console.log(data.sort((a, b) => moment(a.date, "YYYY-MM-DD") - moment(b.date, "YYYY-MM-DD")));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...