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

时间:2020-01-18 03:58:56

标签: javascript arrays node.js multidimensional-array

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

$ git add --interactive foo

*** Commands ***
  1: status       2: update       3: revert       4: add untracked
  5: patch        6: diff         7: quit         8: help
What now> 4
  1: foo/a
  2: foo/b
  3: foo/c
Add untracked>> 1
* 1: foo/a
  2: foo/b
  3: foo/c
Add untracked>> 2
* 1: foo/a
* 2: foo/b
  3: foo/c
Add untracked>> 3
* 1: foo/a
* 2: foo/b
* 3: foo/c
Add untracked>>
added 3 paths

*** Commands ***
  1: status       2: update       3: revert       4: add untracked
  5: patch        6: diff         7: quit         8: help
What now> q
Bye.

$ git status
On branch master

No commits yet

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)

        new file:   foo/a
        new file:   foo/b
        new file:   foo/c

这是我期望的最终输出:

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; } } }) } 函数来遍历数据并生成html。

预期输出:

generatehtml()

我不知道如何从生成的数据生成预期的输出数组。 我该怎么办?

3 个答案:

答案 0 :(得分:1)

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

另一个,使用.map()遍历第一个数组,然后使用.reduce()keywordshtml构建对象,然后{ {3}}放入您的姓名首字母。

我还为每个步骤添加了注释,以使您更轻松。

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

这是您可能要做的事情。

您可以使用以下代码段简化您的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);