Mapping array of objects to an array of Objects with object and array
Solution 1:
You need to iterate through each array element using the reduce
array method, and check if the element is an intent. If it is, push a new object to the result array, if it isn't, just push a new element to the actions array of the last index intent using the .at()
method:
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)