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

Angular in conjunction with socket.io does not immediately show messages on screen

I am currently working on developing an instant messaging app (chat) using socket.io and Angular. I have two main files: index.html and index.js as shown below. The chat functionality is working well, but I am facing an issue where the messages do not appe ...

How can I prevent mouse movement hover effects from activating in a media query?

I have implemented a custom image hover effect for links in my text using mousemove. However, I want to disable this feature when a specific media query is reached and have the images simply serve as clickable links without the hover effect. I attempted ...

Ways to separate a string based on changing values in Javascript

Given this unmodifiable string: "AAACCDEEB" I am looking to split it into an array whenever the value changes. In this scenario, I would end up with 5 arrays like so: [['A','A','A'], ['C','C'], [ ...

Error: Attempting to append to a `dict` object in JSON is not a valid operation

Why isn't the append method working on dictionary objects? Here is my code snippet: with open (file) as f: for line in f: review = json.loads(line) review.append((review['reviewText'],review['overall']))#append ...

Remove specific data from jQuery datatables using data attribute

My jQuery datatable is loaded with data from a database without any filtering by default, providing all the necessary information for users. In addition to the built-in search functionality of jQuery datatables, I have incorporated custom search input fiel ...

Unable to retrieve link text following readFile function. Selector functions properly in Chrome console

My goal is to extract hyperlink text. Using the google chrome console with my selector, I am able to retrieve a list of 15 link texts as desired. However, when I execute my code with the same selector, the el.text returns undefined in console.log while th ...

Error in typescript: The property 'exact' is not found in the type 'IntrinsicAttributes & RouteProps'

While trying to set up private routing in Typescript, I encountered the following error. Can anyone provide assistance? Type '{ exact: true; render: (routerProps: RouterProps) => Element; }' is not compatible with type 'IntrinsicAttribu ...

Connecting to a pathway of Material-UI menu items

I am currently utilizing Material-UI's menu components as part of my project requirements. However, I am encountering difficulties in properly routing each MenuItem to an existing route within my application. As a temporary solution, I have resorted ...

Utilizing NLP stemming on web pages using JavaScript and PHP for enhanced browsing experience

I've been exploring how to incorporate and utilize stemming results with JavaScript and PHP pages on web browsers. After running node index.js in the VS Code terminal, I was able to retrieve the output word using the natural library: var natural = re ...

Exploring the world of Node.js, JSON, SQL, and database tables

Hello everyone, I have been working on a project using Node.js and Express framework. My current goal is to create a client-side page that allows users to input form data into a MySQL database. I have managed to successfully insert and retrieve data from ...

Pass a selected object to a dropdown/select change event using AngularJS

Plunkr : http://plnkr.co/edit/BRQ3I4hFTlgKq4Shz19v?p=preview I'm attempting to pass the selected item from a dropdown to a function within my controller. Unfortunately, I keep receiving it as undefined. HTML : <!DOCTYPE html> <html> ...

The code begins executing even before the function has finished its execution

I believe that is what's happening, but I'm not entirely sure. There's code in a .js file that invokes a function from another .js file. This function performs an ajax call to a php page which generates and returns a list of radio buttons wi ...

What is the reason behind being limited to sending only 5 requests if I fail to heed the data event?

I've come across some related questions while researching this topic, such as Why is node.js only processing six requests at a time?. However, I am still struggling to fully grasp the specifics. Below is a breakdown of my scenario: Firstly, let&apos ...

Is it possible to leverage Create-React-App's npm start in conjunction with Node.js?

I've recently started diving into React and node.js. My goal is to have a node.js server that can serve up React.js pages/views. After running 'create-react-app' and then using 'npm start', I'm not sure if I also need to man ...

Showing a series of JavaScript countdowns consecutively

I am working on a project where I want to display a second countdown after the first one finishes using meteor. The initial timer code looks like this: sec = 5 @timer = setInterval((-> $('#timer').text sec-- if sec == -1 $('#time ...

The width of an HTML input and button elements do not match

Currently, I am facing an unusual issue where my input and button tags seem to have the same width assigned to them (width: 341.5px; calculated from $(window).width() / 4) in the code, but visually they appear to be of different widths. Here is a visual re ...

Is there a way to check if a user has previously visited a URL and automatically redirect them back to that page if they have

I'm looking for a way to detect if a user has already opened a specific link or URL in their browser tab. Is it possible to redirect the link to an active tab if the URL is already open? For example, if a user clicks on a link and JS code opens a new ...

Setting up Visual Studio Code for debugging HTML and JavaScript code

Struggling to troubleshoot some HTML/JavaScript using VSCode. After installing the Chrome debugger extension and configuring the launch.json as follows: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of ex ...

Modifying the content within a DIV element

I want to make changes to my DIV. <div id="main"> <div id="one"> <div class="red"> ... </div> <img class="avatar" src="img/avatar1.jpg"/> <span class="name"> John < ...

Revamp the sequence of divs using jQuery

<div class="example first">111</div> <div class="example second">222</div> <div class="example third">333</div> Can the order of these divs be changed using jQuery? I am looking to get: <div class="example second"&g ...