Extract information from an array located inside a nested object

My aim is to calculate the length of the skills array for each user individually.

To begin, I have this JSON data:

    const txt = `{
    "Alex": {
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e2838e879aa2838e879acc818d8f">[email protected]</a>",
        "skills": [
            "HTML",
            "CSS",
            "JavaScript"
        ],
        "age": 20,
        "isLoggedIn": false,
        "points": 30
    },
    "Asab": {
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2c4d5f4d4e6c4d5f4d4e024f4341">[email protected]</a>",
        "skills": [
            "HTML",
            "CSS",
            "JavaScript",
            "Redux",
            "MongoDB",
            "Express",
            "React",
            "Node"
        ],
        "age": 25,
        "isLoggedIn": false,
        "points": 50
    },
    ... (remaining content omitted for brevity)
}
`

The next step involves parsing it into the userObj variable:

const userObj = JSON.parse(txt, undefined);

However, the issue arises when trying to iterate over the user objects:

for (let user in userObj) {
  console.log(user); //returns string values instead of object references
} 

This leads to unexpected outcomes when attempting to process the data. Despite numerous attempts, a suitable solution has yet to be implemented.

Desired output format:

{ 
    Alex => 3,
    Asab => 7,
    Brooke => 5
}

Answer №1

If the parsing was successful, it shouldn't be causing that issue. Check out this functional code snippet below.

const data='{"Alex":{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e48588819ca48588819cca878b89">[email protected]</a>","skills":["HTML","CSS","JavaScript"],"age":20,"isLoggedIn":false,"points":30},"Asab":{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f796849695b796849695d994989a">[email protected]</a>","skills":["HTML","CSS","JavaScript","Redux","MongoDB","Express","React","Node"],"age":25,"isLoggedIn":false,"points":50},"Brook":{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1571747b7c70795571747b7c70793b767a78">[email protected]</a>","skills":["HTML","CSS","JavaScript","React","Redux"],"age":30,"isLoggedIn":true,"points":50},"Daniel":{"email":"<a hre...

const members = JSON.parse(data);

const result = {};

for (const member in members) {
  console.log(member);
  result[member] = members[member].skills.length;
}

console.log(result);

Answer №2

If you want to achieve this task, you can utilize the Object.keys method:

Object.keys(userData).map((user) => {
  const userInfo = `${user} => ${userData[user].skills.length}`;
  console.log(userInfo);
});

The output will be as follows:

Alex => 3
Ben => 6
Chris => 4
David => 5
Ethan => 7
Frank => 6

To accomplish this, iterate over each key of userData (representing user names) and access the corresponding values to create the desired string.

Answer №3

When using the "for-in" loop, remember that it returns keys in each iteration rather than values. Therefore, to access the objects, use userObj[user].

Answer №4

To begin, you need to convert the JSON data into an object. Next, transform this object into an array so that you can iterate over it. Then, at this stage, you have the ability to output information to the console.

const jsonData = `{
    "Alice": {
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="20414c455860414c45580e434f4d">[email protected]</a>",
        "skills": [
            "HTML",
            "CSS",
            "JavaScript"
        ],
        "age": 20,
        "isLoggedIn": false,
        "points": 30
    },
    "Bob": {
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a3c2d0c2c1e3c2d0c2c18dc0ccce">[email protected]</a>",
        "skills": [
            "HTML",
            "CSS",
            "JavaScript",
            "Redux",
            "MongoDB",
            "Express",
            "React",
            "Node"
        ],
        "age": 25,
        "isLoggedIn": false,
        "points": 50
    },
    "Charlie": {
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6b0f0a05020e072b0f0a05020e0745080406">[email protected]</a>",
        "skills": [
            "HTML",
            "CSS",
            "JavaScript",
            "React",
            "Redux"
        ],
        "age": 30,
        "isLoggedIn": true,
        "points": 50
    },
    // Remaining user objects omitted for brevity
}
`
let userArray = [];
let usersData = JSON.parse(jsonData)
for (name in usersData) {
  const currentUser = {name, skillCount: 0};
  currentUser.skillCount = usersData[name].skills.length
  userArray.push(currentUser);
}

const result = userArray.map(user=>`${user.name} -> ${user.skillCount}`)
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

I need to position a Vue component at the top of the page for a specific view only

How can I ensure that the component SiteHead only appears at the very top of the HomeView page, above the SiteNavigation component? If I place the SiteHead component within the HomeView.vue code, it ends up below SiteNavigation. Here is my App.vue code: & ...

Retrieving Hyperlinks from JavaScript Object for Integration with D3-Created Table

Issue: I'm facing a problem where the HTML link extracted from an Associative Array is treated as a string instead of being applied as a clickable link in the browser. For a detailed visual example and code snippet, visit: http://example.com/code Da ...

Ensure that JSON requests do not contain line breaks within the <div> element

Storing data in a database using json/jquery/ajax has been successful for me. When I retrieve the data in a textarea, it displays exactly as expected. However, loading the data into a DIV results in the absence of line breaks. I have tried various CSS styl ...

Is there a way to load JSON data into an OrderedDict structure?

Is it possible to use an OrderedDict as an output in json.dump? I know it can be used as an input, but I'm curious about maintaining key order when loading into an OrderedDict. If it's not directly possible, are there any alternative solutions o ...

Could Ramda assist in enhancing pipeline/composition processes with a logging feature?

Considering implementing logging within a composed chain of functions, the following code demonstrates how it can be achieved: const f = R.compose( transformation2, doAlso(x => console.log(`id: ${x.id}`)), transformation1 ) This approach would c ...

Utilizing the same uuid twice along with Vuex and the unique identifier generation tool uuidv4

Within my vuex store, there is a function to create a post. This function generates a json Object containing a unique uuid using uuidv4(). However, I have noticed that if I execute the function multiple times, the uuid remains the same each time (unless I ...

All web resources need to be included in the web_accessible_resources manifest key

I'm encountering an issue with my Angular app. The error message on the client console reads: Denying load of chrome-extension://fiekimdgbphfmnlbiahcfdgcipcopmep/js/lib/angular/angular.min.js.map. Resources must be listed in the web_accessible_resour ...

Unable to transform JSON Object into a List

Here are the classes I have: public class Datum { public bool Prop1 { get; set; } public bool Prop2 { get; set; } public bool Prop3 { get; set; } public bool Prop4 { get; set; } public bool Prop5 { get; set; } public bool Prop6 { g ...

Transferring information from offspring to parent

Greetings! I'm currently getting my feet wet with React and finding myself stuck on an issue regarding passing states. Is it possible for me to pass a child state to a parent component in order to selectively render other child components? ...

The perfect method for creating template literals using a function

I have a function that accepts an argument called id and returns a template literal: const generateTemplate = (id) => { return `<div style="box-sizing: border-box; height: 32px; border-bottom: 1px solid #ECECEC; color: #282828; padding: 8px; dis ...

Setting a default value in an arrow function

Currently, I am working on a section of code that renders a simple loading bar. const smallSpinner = document.getElementById('spinner-small').getContext('2d'); let pointToFill = 4.72; let cw = smallSpinner.canvas.width; //Returns canva ...

Attempt to create a truncated text that spans two lines, with the truncation occurring at the beginning of the text

How can I truncate text on two lines with truncation at the beginning of the text? I want it to appear like this: ... to long for this div I haven't been able to find a solution. Does anyone have any suggestions? Thanks in advance! ...

What is the best way to embed PHP code into a jQuery append using AJAX?

After searching for information on "How to insert PHP into jQuery?", I have not been able to find the solution that I need. I have a todo list in php and I am trying to implement ajax functionality into it. When the ajax call is successful, I want to appen ...

Is $timeout considered a questionable hack in Angular.js development practices?

Here's a question for you: I recently encountered a situation where I needed to edit the DOM on a Leaflet Map in order to manipulate the appearance of the legend. To workaround an issue where the map wasn't generating fast enough to access the n ...

Utilize the Masonry layout script on dynamically generated elements from AJAX requests

I have been implementing a Masonry script with the following code: var $container = $('.grid'); $container.imagesLoaded(function(){ $container.masonry({ itemSelector : '.grid-item', columnWidth : '.grid-sizer', ...

What causes the website to malfunction when I refresh the page?

I utilized a Fuse template to construct my angular project. However, upon reloading the page, I encountered broken website elements. The error message displayed is as follows: Server Error 404 - File or directory not found. The resource you are looking fo ...

Having trouble retrieving information from a nested JSON array within a JSON object using JavaScript

I am facing a challenge with extracting specific information from a JSON object that contains an array nested inside. Even though I have experience working with JSON arrays, this particular object is proving to be tricky. For example, when attempting to r ...

Is there a way to compel the browser or JavaScript to delete/disregard a cached file?

I've encountered an issue with my Javascript program that extracts data from a text file and displays it in a table. The problem arises when I update the text file - the changes don't reflect on the table because the browser is caching the file. ...

Error in ReactJS: Trying to access property 'items' of an undefined object

I've been diving into ReactJS, but I've hit a roadblock with this perplexing error. My goal is to update the parent's items array state from its child component. To achieve this, I attempted to pass the addItem function as a prop to the chi ...

Displaying a div upon hovering over another div is resulting in numerous server requests and a flickering effect

I am attempting to create a hover effect where one div floats next to another. The layout of the divs is like a grid, placed side by side. Check out my code on this fiddle. Using plain JavaScript, I want to display a second div (div2) floating next to div ...