繁体   English   中英

循环多维数组以生成新数据并在节点 js/javascript 中附加新键值

[英]Loop over multidimensional array to generate new data and append new key values in node js / javascript

我有一个像这样的对象数组:

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()函数来循环数据并生成 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>"
}]}

我无法弄清楚如何从生成的数据中生成预期的输出数组。 我该怎么做?

有很多方法可以做到这一点,其他用户也证明了这一点。

只是另一个,使用.map()迭代您的第一个数组,然后使用.reduce()使用keywordshtml构建对象,然后将其破坏为您的初始值。

为了让您更轻松,我还对每个步骤进行了评论。

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(''); 

您可以使用.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);

这是您可能会做的事情。

您可以使用以下代码片段简化 for 循环

 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM