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

Leveraging SQL Server JSON properties in EF with the code-first approach

I'm looking to create a database to store information about companies and the cars they manufacture. Instead of using traditional tables, I want to leverage the JSON and NoSQL features of SQL Server 2016. This means having a table for Companies and a ...

Having trouble pinpointing the element with protractor's binding locator

<div class="apiRequestDisplay ng-scope"> <pre class="ng-binding">GET</pre> <pre class="ng-binding">v1/securityprofiles/{securityProfileID} </pre> </div> I am trying to target the specific text within v1/secur ...

Is there a way to repurpose a JavaScript object that gets sent back to the client upon page loading?

Upon initial page load, an AJAX request fetches a list of JavaScript objects which display only one value each. The page includes buttons to expand each item and reveal the remaining values. Originally, I used another AJAX call to retrieve individual objec ...

Modifying `msg.sender` in Solidity and Ether.js

I have a Smart Contract written in Solidity. Within this contract, there is a function called makeMarketItem. function makeMarketItem( address nftContract, uint256 tokenId, uint256 price ) public payable nonReentrant { IERC721(nftContract). ...

What are effective ways to eliminate script tags from a webpage?

I have implemented tags on my website that users can use to interact with the site. My goal is to figure out how to make the browser only read text from a specific file I write, without any HTML. This should be restricted to certain sections of my websit ...

Adobe Acrobat does not run JavaScript code in documents that are submitted for electronic signatures

Lately, I have been experiencing issues with pdfs that contain embedded javascript. The strange thing is that the javascript functions perfectly in the Acrobat Pro DC app but fails to execute when the document is sent for signature. To troubleshoot, I cre ...

Displaying individual attachments with the JSON API on a Wordpress site

Upon accessing the following URL: example.com/api/get_tag_posts/?dev=2&slug=ME3022&include=attachments The response received is: { status: "ok", count: 1, pages: 1, tag: { id: 17, slug: "me3022", title: "ME3022", ...

When the limit is set to 1, the processing time is 1ms. If the limit is greater than 1, the processing time jumps to

Here is the MongoDB Native Driver query being used: mo.post.find({_us:_us, utc:{$lte:utc}},{ fields:{geo:0, bin:0, flg:0, mod:0, edt:0}, hint:{_us:1, utc:-1}, sort:{utc:-1}, limit:X, explain:true }).toArray(function(err, result){ ...

Unable to load the file or assembly 'Newtonsoft.Json.Net35

My program is encountering a runtime exception {"An issue has occurred with loading the file or assembly 'Newtonsoft.Json.Net35, Version=4.0.2.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system is u ...

Page redirects automatically after AJAX call

I'm a beginner when it comes to using AJAX and I am trying to delete a student from a list through an AJAX request. I want the response of the request to be displayed on the same page within a specific div, but instead, the response keeps redirecting ...

Troubleshooting VueJS, Electron, and Webpack integration with Hot Reload feature

I have been immersed in a new project that involves utilizing Electron, VueJS, and Webpack for HMR functionality. Unfortunately, I am encountering difficulties with the Hot Module Replacement feature not working as expected. Here is my current configurati ...

Tips on invoking a mixin within a Jade template showcased in a Node/Express endpoint

I'm currently developing a component that I plan to use multiple times on a website through a Jade template. This is how my route is set up: router.get('/', function(req, res, next) { res.render('indicators',{category:"", num ...

Display the chosen date from the datepicker in the input field

Utilizing a JQuery DatePicker to be constantly displayed, I have assigned it to a div. Despite wanting it to display the selected date in the input box like in this example, it just isn't functioning as desired for me. Is there a way to have the selec ...

Using cakePHP to submit a form using ajax

While submitting a form using ajax and attempting to return a json response, I encountered an issue of receiving a missing view error. Adding autoResponder=false resulted in no response at all. This is happening while working with cakephp 2.5 In the same ...

What is the best way to add a listener for a modification of innerHTML within a <span>?

How can I detect changes inside a particular <span> element in order to attach a handler, but so far have been unsuccessful? Below is the HTML snippet: <span class="pad-truck-number-position"><?php echo $_SESSION['truckId']; ?> ...

Experiencing a glitch with the Realtime Database feature on Firebase

// db.js file import * as firebase from "firebase/app" import "firebase/database" const config = { apiKey: "" ... } const db = firebase.initializeApp(config) export default db // App.vue ...

Even though I have successfully stored a key value pair in LocalStorage using JSON stringify and setItem, the data does not persist after the page is refreshed

I recently developed a Todo application that runs smoothly, except for one crucial issue - the localStorage data does not persist after refreshing the page. Initially, the localStorage operations functioned properly when there were fewer event handlers in ...

Obtain information from a JSON file based on a specific field in Angular

The structure of the JSON file is as follows: localjson.json { "Product" :{ "data" : [ { "itemID" : "1" , "name" : "Apple" , "qty" : "3" }, { "itemID" : "2" , "name" : "Banana" , "qty" : "10" } ] ...

Converting a JavaScript function to CoffeeScript, accepting jQuery's .map function and Selectors as parameters

I'm in the process of converting some JavaScript code into CoffeeScript and encountering an issue with a particular function. Here is the original functioning JS: $(".comformt_QA").change(function(){ var array = $(".comformt_QA").map(function() { ...

Having difficulty requesting an API in Next.js that relies on a backend cookie

1: When a user logs in, I generate a refresh token and create a cookie using 'cookie-parser'. This cookie is then sent to the path '/user/refresh-token' res.cookie('refreshtoken', refreshtoken, { httpOnly: true, ...