[英]Mapping array of objects to an array of Objects with object and array
我有一个 object
const response = {
"message": "story records found successfully",
"result": [
{
"created_AT": "Thu, 13 Jan 2022 17:37:04 GMT",
"created_BY": "avinash",
"dateTime": "Thu, 13 Jan 2022 17:37:04 GMT",
"deleted_BY": "",
"flag": 0,
"project_ID": "infobot1234",
"stories": {
"steps": [
{
"intent": "test"
},
{
"action": "uttence_test_heading"
},
{
"intent": "fruits"
},
{
"intent": "testintent"
},
{
"action": "utter_txt1234"
},
{
"action": "uttence_test_heading"
},
{
"action": "utter_txt1234"
},
{
"intent": "test"
},
{
"intent": "fruits"
},
{
"action": "uttence_test_heading"
},
{
"intent": "my_localities12333qqqwq"
}
],
"story": "happy path rdedd"
},
"stories_ID": "f5728c4f-3717-40c2-8419-265d5d59bfd1",
"updated_BY": "",
"user_ID": "av1234"
}
],
"status_code": 0
}
由此我必须创建一个类似的结构,所以我预期的 output 是
const data = [
{intent: 'test', actions:['uttence_test_heading']},
{intent:'fruits', actions:[]},
{intent:"testintent", actions:["utter_txt1234","uttence_test_heading","utter_txt1234"]},
{intent:"test", actions:[]},
{intent:"fruits", actions:["uttence_test_heading"]},
{intent: "my_localities12333qqqwq", actions:[]}
]
我能得到的最接近的是使用response.result[0].stories.steps
这给了我结果
[{
intent: "test"
}, {
action: "uttence_test_heading"
}, {
intent: "fruits"
}, {
intent: "testintent"
}, {
action: "utter_txt1234"
}, {
action: "uttence_test_heading"
}, {
action: "utter_txt1234"
}, {
intent: "test"
}, {
intent: "fruits"
}, {
action: "uttence_test_heading"
}, {
intent: "my_localities12333qqqwq"
}]
我怎样才能达到我的预期结果我必须使用一些条件或类似Object.keys
的东西,然后应用任何条件,因为对于每个意图都有一个动作,如果没有动作,那么它应该是一个空数组。
我怎样才能达到我的预期结果,请指导!
您需要使用reduce
数组方法遍历每个数组元素,并检查该元素是否为intent 。 如果是,则将新的 object 推送到结果数组,如果不是,只需使用.at()
方法将新元素推送到最后一个索引意图的操作数组:
const steps = [ {"intent": "test"}, {"action": "uttence_test_heading"}, {"intent": "fruits"}, {"intent": "testintent"}, {"action": "utter_txt1234"}, {"action": "uttence_test_heading"}, {"action": "utter_txt1234"}, {"intent": "test"}, {"intent": "fruits"}, {"action": "uttence_test_heading"}, {"intent": "my_localities12333qqqwq"} ]; const result = steps.reduce((acc, e) => { if (Object.keys(e)[0] === "intent") { acc.push({...e, actions: [] }); }else { acc.at(-1).actions.push(e.action) } return acc; }, []); console.log(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.