How come only the final element is being displayed from an array in JavaScript, rather than all of the elements present

I am facing an issue while attempting to extract specific information from a JSON data and create a new array with key-value pairs. However, instead of getting all the elements, it only returns the last one.

Here is my current code snippet:

const input = {
  "file1": {
    "function1": {
      "calls": {
        "105": {
          "file": "file1",
          "function": "function2"
        },
        "106": {
          "file": "file1",
          "function": "function3"
        }
      },
      "points": {
        "106": "106"
      }
    },
    "function2": {
      "calls": {
        "109": {
          "file": "file1",
          "function": "function2"
        }
      },
      "points": {
        "109": "111"
      }
    },
    "function3": {
      "calls": {},
      "points": {
        "132": "135"
      }
    }
  }
}

function transformData(input) {
  let res = [];
  Object.entries(input).map(([fileName, fileObject]) => {
    Object.entries(fileObject).map(([functionName, functionObject]) => {
      Object.entries(functionObject).map(([functionKey, functionValue]) => {
        if (functionKey === "calls") {
          Object.entries(functionValue).map(([callKey, callObject]) => {
            res.push({"source": functionName, "target": callObject['function']});
          });
        }   
      });
    });
  });
  return res;
 }

 const result = transformData(input);
 console.log(result);

The desired output should be an array with source-target pairs where the source corresponds to the key under 'file' (e.g., function1, function2) and the target is the value of the nested key 'function' within the 'calls' key (e.g., function2, function3, function2).

[
  {
    source: "function1",
    target: "function2"
  },
  {
    source: "function1",
    target: "function3"
  },
  {
    source: "function2",
    target: "function2"
  }
]

If anyone could provide guidance on achieving the correct output, it would be greatly appreciated. Thank you for your time.

Answer №1

it is necessary to make a modification in one line like this

 res = [...res,{"source": functionName, "target": callObject['function']}]

Answer №2

It's uncertain how solid your object structure is in terms of being "guaranteed", but if you're aiming to loop through all the keys starting with file*, and extract the function mappings, this code snippet should get the job done.

const input = 
{
  // Your object structure goes here
}

const result = [];

for(const key in input) {
  if (key.includes('file')) {
    const functions = Object.keys(input[key]);
    for (const func of functions) {
      const funcObject = input[key][func];
      for (const call in funcObject.calls) {
        const callObj = funcObject.calls[call];
        result.push({source: func, target: callObj.function});
      }
    }
  }
}
console.log(result);

Answer №3

It appears that the code should be modified to use res += instead of res =. This way, each new item found will be added to the array rather than overwriting it.

Answer №4

let userData = {
  users: [
   {
      firstName: 'Will',
      lastName: 'Jacob',
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9fecfef2eff3fadfecfef2eff3fab1fcf0f2">[email protected]</a>',
      _id: '5e324187b5fdf167a91dfdbb',
      roles: [ 'ward', 'hospital', 'hr' ],
    },
   {
      firstName: 'Theatre',
      lastName: 'Manager',
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="295a484459454c695a484459454c074a4644">[email protected]</a>',
      _id: '5e3cf2f0c631a8788be59fc4',
      roles: [ 'ward' ],
    },
   {
      firstName: 'Cinema',
      lastName: 'Manager',
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ea998b879a868faa998b879a868fc4898587">[email protected]</a>',
      _id: '5e3cf62cc631a8788be59fc5',
      roles: ['hospital', 'hr' ],
    },
    {
      firstName: 'Cinema2',
      lastName: 'Manager',
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2152404c514d446152404c514d440f424e4c">[email protected]</a>',
      _id: '5e3cf62cc631a8788be59fc5',
      roles: ['ward', 'hr' ],
    },
    {
      firstName: 'Cinema3',
      lastName: 'Manager',
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c3f2d213c20290c3f2d213c2029622f2321">[email protected]</a>',
      _id: '5e3cf62cc631a8788be59fc5',
      roles: ['hospital', 'hr' ],
    },
    {
      firstName: 'Cinema4',
      lastName: 'Manager',
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2f5c4e425f434a6f5c4e425f434a014c4042">[email protected]</a>',
      _id: '5e3cf62cc631a8788be59fc5',
      roles: [ 'ward', 'hospital', 'hr' ],
    }
]};

let organizedData = {};
userData.users.forEach((user) => {
    user.roles.forEach((role) => {
        organizedData[role] ? organizedData[role].push(user) : organizedData[role] = [];
    })
})
console.log(organizedData);

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

Ways to align div elements

I am currently in the process of developing my own custom animation player. Utilizing Three.js for object rendering has been successful so far. However, the challenge lies in incorporating control options at the bottom of the player interface (such as play ...

Trouble with the filter function in the component array

I am facing an issue with creating and deleting multiple components. I have successfully created the components, but for some reason, I am unable to delete them when I click on the "delete" button. state = { data: '', todoCard: [], id ...

What are the most effective ways to manage state in form components using React?

As I delve into the realm of best practices for managing state in React components, I find myself grappling with different approaches. Initially, I crafted a form by creating a TextField component structured like this: var TextField = React.createClass({ ...

What is the best way to display a removed item from the Redux state?

Display nothing when the delete button is clicked. The issue seems to be with arr.find, as it only renders the first item regardless of which button is pressed, while arr.filter renders an empty list. reducer: export default function reducer(state = initi ...

Utilizing Node.js to iterate through arrays grouped by categories

Here is some data I need to work with [ [ '@test','1.2.6-unstable' ], [ '@test','1.3.2-unstable' ], [ '@test','1.4.6-unstable' ], [ '@test2','4.0.1-unstable' ], [ &ap ...

Ways to customize the appearance of an iframe's content from a separate domain

I am facing a challenge with my widget and multiple websites. The widget is hosted on one domain, but the websites use an iframe to display it. Unfortunately, because of the Same Origin Policy, I cannot style the content of the iframe from the parent websi ...

Having trouble with gapi.client.request() not functioning properly?

I've been trying to use the Google API for freebase, and even though I'm following the correct call as per the documentation, it seems like there is an issue. The Chrome debugger is showing that something is wrong with this supposedly simple call ...

Utilizing ng-pattern in Angular to detect leading zeroes in alphanumeric input fields

Are you wondering how to identify a leading zero in an alphanumeric field using ng-pattern in angular? <body ng-app> <h1>Regex test</h1> <form name="myForm"> <input name="myNumberField" ng-model="myNumber" ng-pa ...

Managing package versions with package.json and teamcity integration

Our team utilizes TeamCity for builds and deployments. One of our goals is to have TeamCity automatically set the version number in the package.json file. In the past, we used a tool called gulp-bump to update the version number, but TeamCity's build ...

I can't seem to get the post method to work properly for some unknown reason

Hello there, I am encountering an issue while trying to submit a form on my website using the post method. For some reason, it keeps returning a null value. However, when I send data not through the form but instead by reading axios, it works perfectly fin ...

What is the best way to retrieve the current complete URL in a Next.js/Typescript component?

I'm working on a component and I need to retrieve the current full URL. Here's a simplified version of what I have: /** * Share dropdown component */ export const ShareDropdown: React.FC<{ className: string }> = ({ className, }) => { ...

Vue.js is experiencing functionality issues on mobile devices and other connected devices, however, it is operating smoothly on desktop devices when localhost is running

I recently ran into an issue while trying to run my Laravel project on localhost and connect it to other devices like mobiles and desktops/laptops using the local address. The function works perfectly on the hosting desktop but fails to work on other devic ...

The issue arises when a continuous use of angularjs directives linked with an external template fails to display correctly upon the addition of new

In the code snippet below, you'll find a fiddle that displays 3 columns of numbers that increase in value. These columns represent directives with different templates: one inline, one preloaded, and one from an external template. When you click on the ...

The action is not being added to the HTML when the click event is triggered

I'm developing a GIF generator, with the aim of generating clickable buttons that will dynamically add 10 gifs based on the search term to the page. Although the click event is triggering the console log, it's not adding divs with gif images and ...

Struggling with updating an array in state using setState?

Currently, I am working on a React app that involves taking user input, filtering array data based on that input, and updating another field in the same data. However, I have encountered difficulties when trying to use setState to make these changes. Addit ...

unable to access the object3D within the current scene

Currently facing an issue where I am unable to retrieve Object3D from the scene, despite the mesh objects being displayed within the scene. Strangely, the scene.children array does not reflect this. Take a look at the screenshot here Here is the code sni ...

Can AJAX be exploited by hackers?

Today, I had a fascinating experience with my built systems. Someone managed to "hack" into everything and attributed the issue to AJAX. Here are his exact words: you are relying on AJAX when I have access to user's browser I have acc ...

Employing $http.post in conjunction with res.redirect without handling the promise fulfillment

When making an $http.post call to my server, I send user data like this: $http.post('/streamdb/create/',{user:$scope.user.username}) After performing some operations on the server and retrieving a specific id from the DB, I want the client to b ...

The text content is not in alignment with the server-rendered HTML for translation purposes with i18n

I have successfully implemented i18n in my Next.js project. The folder structure for my locales is as follows: public/locales/en/translation.json and public/locales/fr/translation.json The error I am encountering is: Uncaught Error: Text content does n ...

Node.js using Express: Modifying response data for specific route

I've searched through numerous resources but haven't been able to find a solution, so I'm reaching out for some assistance! :) I have developed a UI5 Application using Node.js with Express on the server-side. The data is retrieved from a SQ ...