L oop над многомерным массивом для генерации новых данных и добавления новых значений ключа в node js / javascript - PullRequest
1 голос
/ 18 января 2020

У меня есть массив таких объектов:

var finalresult = [{
    "Date": "Wed Jan 15 2020 00:00:00 GMT+0530 (India Standard Time)",
    "data": [{
            "intent": "delivery",
            "result": [{
                "heading": "Delivered",
            }]
        },
        {
            "intent": "orders",
            "result": [{
                "heading": "What is the order status"
            }]
        },
        {
            "intent": "orders",
            "result": [{
                "heading":"Where is my order"
            }]
        }
    ]
},{
    "Date": "Wed Jan 17 2020 00:00:00 GMT+0530 (India Standard Time)",
    "data": [{
            "intent": "feedback",
            "result": [{
                "heading": "Hello",
            }]
        },
        {
            "intent": "feedback",
            "result": [{
                "heading": "You are good"
            }]
        },
        {
            "intent": "picnic",
            "result": [{
                "heading":"Lets go on picnic"
            }]
        } ,
        {
            "intent": "picnic",
            "result": [{
                "heading":"Are you coming for the picnic?"
            }]
        } ,
        {
            "intent": "order",
            "result": [{
                "heading":"When should I pick my order"
            }]
        }
    ]
}]

Это конечный результат, который я ожидаю:

[{
    "Date": "Wed Jan 15 2020 00:00:00 GMT+0530 (India Standard Time)",
    "keywords" : "delivery,orders",
    "html" : "<h1>Delivered</h1><h1>What is the order status</h1><h1>Where is my order</h1>"
},{
    "Date": "Wed Jan 17 2020 00:00:00 GMT+0530 (India Standard Time)",
    "keywords" : "feedback,picnic,order",
    "html" : "<h1>Hello</h1><h1>You are good</h1><h1>Lets go on picnic</h1><h1>Are you coming for the picnic?</h1><h1>When should I pick my order</h1>"
}]

Это то, что я пробовал до сих пор:

    var chatstring = "";
    var final = [];
    keywordset = new Set();
    // console.log(JSON.stringify(finalresult))
    for (i = 0; i < finalresult.length; i++) {
        ////chatarr +="<div class='collapsible'></div>";
        for (j = 0; j < finalresult[i].data.length; j++) {
            //console.log(finalresult[c].data)
            keywordset.add(finalresult[i].data[j].intent);
            // console.log(summary);
            generatehtml(finalresult[j].data)
            nloop++;
            if (nloop == (finalresult.length)) {

               final.push(chatstring)
            }
        }

        //forEach
    }

    function generatehtml(data) {
    return new Promise((resolve, reject) => {
        for (s = 0; s < data.length; s++) {

            for (t = 0; t < data[s].result.length; t++) {
                var response = data[s].result[t].heading;
                  var html = "<div" + response + "</div>";
                  chatstring += html;
            }

        }

    })
}

Я использую набор для хранения уникальных значений намерений. Я использую функцию generatehtml(), чтобы l oop поверх данных и генерирую html.

Ожидаемый результат:

{"chat": [{
    "Date": "Wed Jan 15 2020 00:00:00 GMT+0530 (India Standard Time)",
    "keywords" : "delivery,orders",
    "html" : "<h1>Delivered</h1><h1>What is the order status</h1><h1>Where is my order</h1>"
},{
    "Date": "Wed Jan 17 2020 00:00:00 GMT+0530 (India Standard Time)",
    "keywords" : "feedback,picnic,order",
    "html" : "<h1>Hello</h1><h1>You are good</h1><h1>Lets go on picnic</h1><h1>Are you coming for the picnic?</h1><h1>When should I pick my order</h1>"
}]}

Я не могу понять, как сгенерировать ожидаемый выходной массив из сгенерированных данных. Как мне это сделать?

Ответы [ 3 ]

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

Есть много способов сделать это, что продемонстрировали и другие пользователи.

Просто еще один, используя .map() для перебора вашего первого массива, а затем .reduce() для построения объекта с keywords и html, который затем уничтожается в вашей начальной букве.

Я также включил комментарии к каждому шагу, чтобы вам было легче.

finalresult.map(result => ({ // this will be our final object
  Date: result.Date,
  ...result.data.reduce((accumulator, current) => { // looping through our data
    if (!accumulator.keywords.includes(current.intent)) { // if intent not already in our keywords
       if (accumulator.keywords.length) accumulator.keywords += ','; // if keywords has at least one, add `,`
       accumulator.keywords += current.intent; // add our new keyword
    }

    /** on the next line we map result in case 
     *  array has more than 1 object. We build the 
     *  string we need and while map will return 
     *  an array we use join (with empty string as separator) 
     *  to create a string from our array
     **/
    accumulator.html += current.result.map(res => `<h1>${res.heading}</h1>`).join(''); 

    return accumulator;
  }, { // our initial object, that will be filled be reduce and the destructed into our upper object
    keywords: "",
    html: ""
  }
)
}))

РЕДАКТИРОВАТЬ: После просмотра комментариев OP, поскольку может получиться получить другой ключ, а не heading, функция / анализатор, создающая правильный вывод, будет чище.

Следующее также покроет несколько клавиш под одним и тем же объектом.

function myhtmlparser (res) {
  const html = [];

  Object.keys(res).forEach(key => {
    switch (key) {
      case 'heading':
        html.push(`<h1>${res[key]}</h1>`);
        break;
      case 'paragraph':
        html.push(`<p>${res[key]}</p>`);
        break;
    }
  })

  return html.join('');
}

И затем используйте его на вашем accumulator.html += ...:

accumulator.html += current.result.map(res => myhtmlparser(res)).join(''); 
0 голосов
/ 18 января 2020

Вот то, что вы могли бы потенциально сделать.

Вы можете упростить свой код для l oop с помощью следующего фрагмента кода

finalresult.forEach((val) => {
  const output = {};
  output['Date'] = val.Date;
  const intents = [];
  const htmls = [];
  val.data.forEach((obj) => {
    intents.push(obj.intent);
    htmls.push(`<h1>${obj.result[0].heading}</h1>`)
  });
  output.keywords = intents.join(',');
  output.html = htmls.join('');
  result.push(output);
});

var finalresult = [{
  "Date": "Wed Jan 15 2020 00:00:00 GMT+0530 (India Standard Time)",
  "data": [{
      "intent": "delivery",
      "result": [{
        "heading": "Delivered",
      }]
    },
    {
      "intent": "orders",
      "result": [{
        "heading": "What is the order status"
      }]
    },
    {
      "intent": "orders",
      "result": [{
        "heading": "Where is my order"
      }]
    }
  ]
}, {
  "Date": "Wed Jan 17 2020 00:00:00 GMT+0530 (India Standard Time)",
  "data": [{
      "intent": "feedback",
      "result": [{
        "heading": "Hello",
      }]
    },
    {
      "intent": "feedback",
      "result": [{
        "heading": "You are good"
      }]
    },
    {
      "intent": "picnic",
      "result": [{
        "heading": "Lets go on picnic"
      }]
    },
    {
      "intent": "picnic",
      "result": [{
        "heading": "Are you coming for the picnic?"
      }]
    },
    {
      "intent": "order",
      "result": [{
        "heading": "When should I pick my order"
      }]
    }
  ]
}];


const result = [];
finalresult.forEach((val) => {
  const output = {};
  output['Date'] = val.Date;
  const intents = [];
  const htmls = [];
  val.data.forEach((obj) => {
    intents.push(obj.intent);
    htmls.push(`<h1>${obj.result[0].heading}</h1>`)
  });
  output.keywords = intents.join(',');
  output.html = htmls.join('');
  result.push(output);
});

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

Вы можете использовать .map() для перебора входного массива и преобразования каждого объекта в требуемый формат:

const data = [{
  "Date":"WedJan15202000:00:00GMT+0530(IndiaStandardTime)",
  "data":[{"intent":"delivery","result":[{"heading":"Delivered",}]},{"intent":"orders","result":[{"heading":"Whatistheorderstatus"}]},{"intent":"orders","result":[{"heading":"Whereismyorder"}]}]
  }, {
  "Date":"WedJan17202000:00:00GMT+0530(IndiaStandardTime)",
  "data":[{"intent":"feedback","result":[{"heading":"Hello",}]},{"intent":"feedback","result":[{"heading":"Youaregood"}]},{"intent":"picnic","result":[{"heading":"Letsgoonpicnic"}]},{"intent":"picnic","result":[{"heading":"Areyoucomingforthepicnic?"}]},{"intent":"order","result":[{"heading":"WhenshouldIpickmyorder"}]}]
}];

const result = data.map(o => ({
  Date: o.Date,
  keywords: [...new Set(o.data.map(({ intent }) => intent))],
  html: `<h1>${[].concat(...o.data.map(({ result }) => result))
                                  .map(({ heading }) => heading)
                                  .join("</h1>")}</h1>`
}));

console.log(result);
...