Converting an array of objects into an array of Objects containing both individual objects and arrays

I am dealing with an 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
    }

I need to organize this data into a specific structure, here is my expected 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:[]}
                 ]

The closest result I obtained so far was using response.result[0].stories.steps, which gave me the following:

[{
  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"
}]

To achieve my desired result, do I need to implement any conditions or utilize Object.keys and then apply certain conditions? Each intent should have corresponding actions, otherwise it should be represented as an empty array.

Your guidance on how to attain the expected result will be greatly appreciated!

Answer №1

To accomplish this task, you will need to loop through each element in the array by utilizing the reduce method specific to arrays. Within the iteration process, you should check if the current element represents an intent. If it does, a new object should be appended to the resultant collection; otherwise, a new entry should simply be added to the actions array of the last intent index using the .at() function:

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)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using PHP to pass both string and integer values into a JavaScript function

I am attempting to pass both a string and an integer into the same function, but I am running into issues with quotes. After some troubleshooting, I realized that the problem lies in the echo $q->info part of my code - I need to use double quotations fo ...

What is preventing me from loading Google Maps within my Angular 2 component?

Below is the TypeScript code for my component: import {Component, OnInit, Output, EventEmitter} from '@angular/core'; declare var google: any; @Component({ selector: 'app-root', templateUrl: './app.component.html', st ...

Make sure to include the onBlur and sx props when passing them through the slotsProp of the MUI DatePicker

This DatePicker component is using MUI DatePicker v6. /* eslint-disable no-unused-vars */ // @ts-nocheck import * as React from 'react'; import { Controller } from 'react-hook-form'; import TextField from '@mui/material/TextField&a ...

Experience seamless transitions with Material UI when toggling a single button click

When looking at the examples in the Material UI Transitions documentation, I noticed that there are cases where a button triggers a transition. In my scenario, I have a button that triggers a state change and I want the previous data to transition out befo ...

The art of defining PropTypes for the style attribute in Reactjs

Is there a way to pass the 'style' attribute into my component using JSX syntax? <InputTextWithValidation id="name" style={{width:'100%'}} .../> I'm wondering how I should define the PropTypes for ...

Tips for featuring the latest blog post at the top of a NextJS blog

I have a website built on Next JS with a blog page. The setup is correct, where the /blog page displays content based on slugs. Currently, new blog posts are appearing at the bottom of the page, under older ones. I want to reverse this so that when a new p ...

What is the most effective method for obtaining only the "steamid" from an AJAX request (or any other method)?

I have been attempting to extract only the "steamid" from an AJAX link without success. Could someone please provide some assistance? Here is the link to find and retrieve only the "steamid": here This is the code I have tried: var xhttp = new XMLHt ...

Code in JavaScript: Generating Random Number within a Loop

Can anyone help me come up with a unique JavaScript loop that can guess a correct number within the range of 1-500? I want each iteration of the loop to generate a new number that has not been guessed before, but it should guess in a random order. For ex ...

AngularJS 1.7.x's ngRoute tabs navigation post authentication

In my current project, I am using ngRoute to route users to the login page and upon successful login, they should land on the dashboard page. However, I am facing a problem with the dashboard page where I need to have two or more tabs that render HTML pag ...

Incorporate the key as a prop within a Child Component in a React application

I am trying to display a list of elements in React, where the key of each element is used as an index in front of the item. However, when I try to access props.key, it just returns undefined. Does anyone have any suggestions on how to access the key proper ...

Encountering an Issue Executing Selenium Test on jQuery v2.0.2 and Play Framework

While I may not be a selenium expert, it seems that I've stumbled upon a bug when trying to utilize jQuery v2.0.2 with my Play Framework 2.2.1 application instead of the default jQuery v.1.9.0. Whenever I run "play test", I encounter the following err ...

Tips for setting a unique JWT secret in next-auth for production to prevent potential issues

Is there a way to properly set a JWT secret in NextAuth.js v4 to prevent errors in production? I have followed the guidelines outlined in the documentation, but I am still encountering this warning message without any further explanation: [next-auth][warn] ...

When you duplicate the React State object and make changes to the copied object, it directly affects

When attempting to duplicate a state object, I noticed that the state object is being modified directly in the code snippet below: @boundMethod private _onClickDeleteAttachment(attachmentName: string): void { console.log("_onClickDeleteAttachment | th ...

Using a dojo widget within a react component: A beginner's guide

Has anyone found a way to integrate components/widgets from another library into a react component successfully? For example: export default function App() { const [count, setCount] = useState(0); return ( <button onClick={() => setCount(count + ...

Removing the root component in ReactJS can be done on specific pages by implementing

Is there a way to remove the <header/> and <footer/> components from my signup.js and signin.js pages without altering the root index.js file? Presently, the root index.js file looks like this: class Template extends React.Component { render( ...

Page jumping vertically in Chrome upon reload, with Firefox and Internet Explorer functioning properly

Utilizing this jQuery script, I am able to center a website vertically within the browser window if it exceeds the height of the outer wrapper-div, which has fixed dimensions. $( document ).ready(function() { centerPage(); )}; // center page vertic ...

TinyMCE - Optimal Approach for Saving Changes: keyup vs onChange vs blur

In the context of my Filemaker file, I am utilizing the TinyMCE editor. My goal is to automatically save any changes made by the user, whether it's typing, applying formatting, inserting an image, or making any other modifications. I have a function ...

Developing a tool for switching between languages in an internationalization application

I have been exploring the implementation of Lingui(i18n) in apps. All set up, but I'm interested in adding a language switcher to enable users to change between language catalogs on my app. Here's my index.js file: import React, { useEffect } fr ...

I'm new to Angular, so could you please explain this to me? I'm trying to understand the concept of `private todoItems: TodoItem[] = []`. I know `TodoItem` is an array that

//This pertains to the todoList class// The property name is todoItems, which is an array of TodoItem objects fetched from the TodoItem file. I am unable to make it private using "private todoItems: TodoItem[] = []," is this because of Dependency Injectio ...

Cross-origin request headers not permitted by the Access-Control-Allow-Headers policy in NodeJS and ExpressJS

I am currently facing an issue with my NodeJS + ExpressJS client-server setup while making API requests to a backend server. Every time I make an API request, I receive the following error: Request header field firstname is not allowed by Access-Control-A ...