Discover how to retrieve an array of objects by utilizing the Object.keys() and map() functions in JavaScript

How can I iterate through an array of objects with a specific structure? My goal is to construct a tree representation of the data, starting with the languages object in each entry and recursively accessing its nested objects using Object.keys() and map().

I am currently experimenting with the following approach:

var productMap2 = {};

productMap2 = Object.keys(jsonData[0]).map(function(key) {
    return jsonData[0][key];
});

Below is the JSON data I am working with:

var jsonData = [
{
"id": 1,
"project_name": "Project101-updated TODAY",
"created_by": "John Doe",
"updated_by": "Wes Smith",
"created_date": "2018-01-09T15:49:54Z",
"updated_date": "2018-01-09T15:49:54Z",
"is_deleted": false,
"languages": [
{
"id": 1,
"language": "English",
...
}
]
},
{
"id": 2,
"project_name": "Project102-updated",
"created_by": "Sammy Sosa",
"updated_by": "Wes Smith",
"created_date": "2018-01-05T03:13:08Z",
"updated_date": "2018-01-05T03:13:08Z",
"is_deleted": false,
"languages": [
{
"id": 2,
"language": "Traditional Chines",
...
}
]
},
{
"id": 10,
"project_name": "Project103-updated",
"created_by": "JOHN doe",
"updated_by": "Wes Smith",
"ceated_date": "2018-01-05T03:13:08Z",
"updated_date": "2018-01-05T03:13:08Z",
"is_deleted": false,
"languages": [
{
"id": 3,
"language": "Simplified Chines",
...
}
]
}
];

Answer №1

Array.prototype.reduce is a fantastic tool, offering both convenience and power for this particular task...

var data = [ {
  "id": 1,
  "name": "Project101",
  ...
    }, {
      "id": 2,
      "phase_name": "Phase2",
      ...
        } ]
 
.as-console-wrapper { max-height: 100%!important; top: 0; }

Answer №2

Creating a tree involves recursion, and when working with arrays in the structure, it can be challenging to visualize on paper with unnamed or numbered elements. One approach is to assign names to array elements based on their values (e.g., using "language" from the "languages" array and "phase_name" from the "details" array) for better representation in the tree.
To address this, defining a TreeNode structure like:

TreeNode{
  'name': string,
  'value': string, //null if children exist
  'children': [TreeNode], //null if value exists
  'expanded': boolean //not applicable if value exists
}

In my past experience, I utilized recursive functions to convert structures into this format, considering different approaches for objects and arrays. By determining the value type for each object key and using recursive functions to create child nodes, a functional tree structure was successfully achieved.

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

Extract the internal JSON data from each variable

Working with large json data sets can be challenging. Each dataset contains Name, Type, and Value fields. Parsing the data to only retrieve items where the Type is "Shirt" is proving to be difficult as I am unsure how to navigate the nested json structure. ...

Viewing a document generated using the Google Drive API using the Google Drive Viewer

Using the Google Drive API, I am able to generate a document and receive some URLs: alternateLink : https://docs.google.com/document/d/xxxsome_idxxxxx/edit?usp=drivesdk embedLink https://docs.goo ...

Dropping anchor whilst skipping or jumping

One of my website elements is a drop anchor that connects from a downwards arrow situated at the bottom of a full-page parallax image to another section on the same page. The HTML code snippet for the drop anchor is as follows: <section id="first" cla ...

Maximizing Screen Size for Videos on Internet Explorer: A Step-by-Step Guide

How can I make the video background fit properly on all browsers, including IE, without zooming it? Here is my website link: The CSS property object-fit: cover works for most browsers, but unfortunately IE does not support this property. I would apprecia ...

Placing an exit button beside an image for easy navigation

Here is a snippet of my code: <style type="text/css"> .containerdiv { position:relative;width:100%;display:inline-block;} .image1 { position: absolute; top: 20px; left: 10px; } </style> <div class="containerdiv"> <ima ...

A guide on shading specific faces based on their normal vectors' alignment with the camera's view

https://i.sstatic.net/FG4hp.png I'm currently working on a shader that requires darkening the faces with normals perpendicular to the camera (dot product is 0). How can I calculate this dot product and make sure it works correctly? uniform float tim ...

Animating SVG elements with the rotation property in SVG.js

Currently, I am utilizing Javascript, Jquery, SVG, and SVG.js in my project. My goal is to rotate a circle around its origin while it's animating. The issue arises when the animation keeps restarting abruptly, causing a jittery motion. Here is the ini ...

Having difficulty obtaining the necessary indexes from several NumPy arrays

I am trying to find the index of the last array (d) where the elements are smaller than 20, but those indices should be within a region where elements of array 'a' are 1 and both arrays 'b' and 'c' have values other than 1. H ...

What is the best way to utilize a variable across all functions and conditions within an asynchronous function in Node.js?

I need to access the values of k and error both inside and outside a function. Initially, I set k to 0 and error to an empty string, but unexpectedly, the console prints out "executed". var k = 0; var error = ""; const { teamname, event_name, inputcou ...

What is the best way to set up distinct Jest test environments for React Components and Backend API routes within NextJs?

In the realm of testing with NextJS, Jest comes into play effortlessly, complemented by React Testing Library for frontend testing. Interestingly, Jest can also be utilized to test backend code. Currently, I am incorporating a library in my API routes tha ...

Obtaining dynamic text from an animated gif image using Java for Selenium automation

https://i.sstatic.net/hLXva.gif I am looking to extract all the text from this gif image and then confirm the accuracy of certain text. ...

What is the best MySQL data type for storing JavaScript code with PHP?

I am creating a platform that resembles jsfiddle, allowing users to store their JavaScript codes and retrieve them in an organized manner. I am unsure about which data type would be most suitable for saving the codes, or if storing them in text files wou ...

Getting a particular attribute and adding it to a collection in backbone.js: The solution explained

With the given JSON structure, I am looking to extract a specific attribute and store it in a collection. The data is formatted as follows: { foo: "lorem ipsum", bars: [{ a: "a", b: {c: "d", e: "f"} }, { a: "u", b: {w: ...

"Create dynamic tables with AngularJS using ng-repeat for column-specific rendering

I have a model called Item with the following structure: {data: String, schedule: DateTime, category: String} I want to create a report that displays the data in a table format like this: <table> <tr> <th>Time Range</th&g ...

How can we use response.render in Express.js to render HTML on the client side?

I have set up a simple Express.js application with the following routes: router.get('/', function(req, res){ res.render('login'); }); Everything is working fine - when I log into the main page on my localhost, the HTML fro ...

Can a Node.js application be configured to accept user input from an external text editor?

Currently working on a Node.js application where I need to integrate an external text editor such as VSCode. The goal is to prompt the user to input text and save it, then have the app retrieve the saved data from the text editor as stdin. Essentially, it& ...

Enhance your Autocomplete feature in jQuery UI by including additional parameters and customizing the returned

Hello everyone, I have recently switched to using the UI Autocomplete instead of the plugin. It took me some time to understand the additional parameters based on an example I found here, but that part is now working for me. However, I am facing issues w ...

Enhance parent style when child's data-state or aria-checked attributes are updated in React using Styled Components

Within a label, there is a button embedded as shown below: <MyLabel htmlFor='xx' onClick={() => onChange}> <MyButton id='xx' {...rest} /> Check it! </MyLabel> In the Developer Tools Elements section, the st ...

Encountering issues with running `npm start` following the creation of a fresh React project using create

Encountering an issue with react-scripts after setting up a new react project. I initiated the project using npx create-react-app dashboard. Upon entering the dashboard directory and executing npm start (without any prior actions), the following error is d ...

Enhance my code to eliminate repetitive elements

Check out this unique plant array: export const uniquePlants = [ { name: 'monstera', category: 'classique', id: '1ed' }, { name: 'ficus lyrata&ap ...