Loop does not occur when using Object.keys(data).forEach

Attempting to extract a value from a JSON object.

var data={
"1":[{"departmentID":1,"departmentName":"Adminstration","branchId":1,"branchName":"ABC"}],
"2":[{"departmentID":2,"departmentName":"HR","branchId":2,"branchName":"DEF"}]
};


Object.keys(data).forEach(function(element, key, _array) {                      
    console.log("branchId: "+element+" "+"BranchName : "+data[element][key].branchName)

    for(dept of data[element]) {
            console.log("Department name : "+dept.departmentName)
    }  
});

The current output shows the first result only and throws a "branchName is undefined" exception.

However, when the JSON object has multiple objects, it works correctly.

var data={
"1":[{"departmentID":1,"departmentName":"Adminstration","branchId":1,"branchName":"ABC"}],
"2":[{"departmentID":2,"departmentName":"HR","branchId":2,"branchName":"XYZ"},
     {"departmentID":3,"departmentName":"Food","branchId":2,"branchName":"XYZ"}]
}

As a newcomer to JavaScript, I have been unable to resolve this issue despite trying various references. Any help in solving this problem would be greatly appreciated. Thank you in advance.

Answer №1

The initial outcome is the only one and results in an undefined exception for branchName.

You should substitute

data[element][key].branchName

with

data[element][0].branchName

This change is necessary because

  • element corresponds to key "1",

  • thus data[element] transforms into

    [{"departmentID":1,"departmentName":"Administration","branchId":1,"branchName":"ABC"}]
    ,

  • data[element][0] becomes

    {"departmentID":1,"departmentName":"Administration","branchId":1,"branchName":"ABC"}

  • ultimately data[element][0].branchName will be "ABC"

Answer №2

You seem to have a mix-up with your keys and values in the data structure. Consider using Object.values, which is available in ES8, to isolate the values and separate them from the keys. Then, you can loop through these values to construct your desired strings.

const data = {
"1":[{"departmentID":1,"departmentName":"Adminstration","branchId":1,"branchName":"ABC"}],
"2":[{"departmentID":2,"departmentName":"HR","branchId":2,"branchName":"DEF"}]
}

Object.values(data).forEach(function(values) {    

   values.forEach(value => {
      console.log(`branchId: ${value.branchId} BranchName: ${value.branchName} Department Name: ${value.departmentName}`);
   });

});

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

What is the best way to trigger a re-render of an app following a mutation?

I am currently working on a React application using Next.js. One of the features I am trying to implement is the ability for users to log in and trigger a re-render of the app to fetch the current logged-in user. Within my _app.js component, I have wrappe ...

Display drop-down item when selected for the first time and hide it when selected for the same item for the second time

Is there a way to display form input when "C" is selected and hide it when "A", "B", or "D" are selected? If "C" is selected again after initially showing the form input, should it be hidden? For example, if "C" is selected for the first time, the form inp ...

Overlap of sub menus

Seeking assistance from a CSS expert for a challenge I am facing. I am currently working on a toggle menu for mobile view, and encountering issues with the submenu. Any list item placed below another one with children is not visible. Removing the parent l ...

Is there a solution to resolve the Firestore issue stating: "FieldPath.documentId is not a recognized function"?

In my function, I am retrieving data from two collections in Firestore: Media and Users. Inside the Users collection, there is a subcollection containing a list of all the user's movies. The Media collection includes details about each movie. My goal ...

Experiencing a problem with XAMPP? Changes made to the code are not reflected after saving

Recently, I've encountered a strange issue with my XAMPP test server while working on a game project. Everything was running smoothly until I noticed that when I make changes to certain files in Notepad++ and save them, the updates are not being refle ...

What is the best way to apply attributes to all titles throughout a webpage?

My goal is to locate all elements on the page that have a title attribute and add a new attribute to each of them. For example: <div title='something 1'></div> <p>Test<div title='something 2'></div></p ...

Transform Microsoft Word file into an array using C#

I am looking to extract data from a table in a Microsoft Word Document (.docs) with dimensions N x M. Does anyone know how I can read this table using C# and store all the values in a 2-dimensional array of size N x M? ...

Express.js Passport.js throws an error when req.user is not defined

The middleware function below is unable to access req.user or determine if the user is logged in after they log in. I have confirmed that passport.serializeUser is successful after logging in and that req is defined when accessed from the middleware funct ...

Is it possible to customize the width of text color alongside a progress bar?

My Bootstrap 4 Website contains the following HTML code snippet: <div class="container"> <div class="row"> <div class="col-md-6 mx-auto> <h2>Example heading text</h2> <h6>Example subh ...

the transparency feature in three.js is completely malfunctioning

I've been browsing through some questions that have already been asked by others here, and one that caught my attention is: Transparent background with three.js I am struggling to make the background transparent instead of black as described in the ...

The unexpected behavior of string.matchAll(regex) in web browsers

Struggling to use a regular expression to match markdown in node.js, but facing issues when attempting to run it in a react.js app... const regex = /(\*\*\*|___|\*\*|\*|__|\[.*?\]\([^)]*\))(.*?)(\1|$ ...

Enhancing VueJS2 components by optimizing code structure to eliminate duplicate elements

The following code is used in two different components, so please avoid using props. Utilize data variables and largely similar methods but with different component templates. <template> </template> <script> export default { name ...

From Beginner to Expert: Mastering AngularJS in Chapter 4

I've been diving into the sitepoint ANGULARJS: NOVICE TO NINJA book and I've hit a roadblock with the final example in chapter 4. In this application, the default angular ngRoute module is swapped out for the more robust Angular UI Router module. ...

Tips for navigating through an array of images

I am attempting to create a feature similar to Snapchat stories, where an array of images is displayed for a set amount of time before returning to the previous screen. Here is an example code snippet: if (images.length > 0) { let timeout; ...

Utilize text wrapping to ensure a fixed maximum height for content display

I am in need of a div that contains text spanning multiple lines, with both a fixed width and a maximum height. Currently, I have applied the CSS property overflow: hidden;. However, my issue arises when the last line of text exceeds the maximum height of ...

Tips for crafting a perpetually looping animated shape using canvas

Lately, I've been experimenting with canvas and have encountered a challenge that I can't seem to solve. I've mastered creating shapes, animating them, and looping them across the canvas. However, I'm struggling to figure out how to spa ...

PHP Arrays - the everlasting reference

Is it possible to create a PHP array that is always treated by reference without the requirement of using the & operator? For example: $arr1 = ref_array('x', 'y', 'z'); $arr2 = $arr1; $arr2[] = 'w'; should res ...

What is the best way to structure a data object in Javascript or VueJs?

As I work on developing a small application using VueJs, the data I receive is structured in a particular format: { "interactions":[ { "id":14, "user_id":1, "schedule":"2017-06-04 05:02:12", "typ ...

Challenges with Json deserializing String arrays in C# Entity Framework

I am encountering an issue with deserializing a Json file to Entity framework. To simplify, let's assume the Json structure looks like this: { "stat": "val0", "results": [ { "datasets": [ "val1", "val2" ], "h ...

Why does jwplayer function properly on desktops but not consistently on all mobile devices?

Here is how I set it up: autostart:true file:"//strlb.nava.hu/lbs/navahus/_definst_/amlst:2334206?type=m3u&sessid=U2FsdGVkX1%2BT8isbmDU7Vz56rK8KVCo2xKgOLwwR5JUSq5m5GfKrL4HM%2FrbhwdyJJ0gyyK0X6%2FrAbTjfnsBAqg%3D%3D_2" height:360 id:"videoPlayer" preloa ...