Tips for organizing an Array of Arrays in JSON for improved structure

Consider the JSON object shown below:

var workers = { "finance" : [   // finance is an array in workers.
                                { "firstName" : "Alice",  // First element
                                  "lastName"  : "Smith",
                                  "age"       : 28 },

                                { "firstName" : "Tom",  // Second Element
                                  "lastName"  : "Brown",
                                  "age"       : 35 }
                              ], // End "finance" array.                                  
              "marketing"       : [ // Marketing is another array in employees.
                                { "firstName" : "Linda", // First Element
                                  "lastName"  : "Taylor",
                                  "age"       : 30 },

                                { "firstName" : "Kevin",   // Second Element
                                  "lastName"  : "Jones",
                                  "age"       : 39 }
                              ] // End "marketing" Array.
            } // End Workers

To access each employee's first name individually, you need to restructure the object as follows:

workers.finance[0].firstName
workers.finance[1].firstName
// etc

Answer №1

To restructure this, you would need to remove the "accounting/sales" properties and convert employees into an Array of Objects.

For example: http://jsfiddle.net/hgMXw/

var employees = [
    {
    "dept": "accounting", // new property for this object
    "firstName": "John",
    // First element
    "lastName": "Doe",
    "age": 23
    },
    {
    "dept": "accounting", // new property for this object
    "firstName": "Mary",
    // Second Element
    "lastName": "Smith",
    "age": 32
    },
    {
    "dept": "sales", // new property for this object
    "firstName": "Sally",
    // Third Element
    "lastName": "Green",
    "age": 27
    },
    {
    "dept": "sales", // new property for this object
    "firstName": "Jim",
    // Fourth Element
    "lastName": "Galley",
    "age": 41
    }
] 

Answer №2

To handle this situation differently, you need to restructure your code. Consider either incorporating the department as a key in the employee object or accessing it using employees.accounting[0].firstName instead.

If you still want to access the employee as employees[index], you will need to rearrange it as follows:

var employees = [
  { "firstName" : "John", "lastName" : "Doe", "age" : 23, "department" : "accounting" },
  { "firstName" : "...", ..., "department" : "accounting" },
  ... and so forth.
];

Additionally, you can implement a different method for filtering by department.

One approach could be to create a function that iterates through the employees array, filters out matching elements, and returns them in a new array object.

function getAllEmployeesFilteredBy(filterName, filterValue, empArray)
{
  var result = [];
  for (var i=0; i < empArray.length; i++) {
    if (empArray[i][filterName] === filterValue)
      //by reference
      result[result.length] = empArray[i];

      //or by value (creating a new object)
      //result[result.length] = { "firstName" : empArray[i].firstName, "lastName" : empArray[i].lastName, ... }
  }
  return result;
}

Answer №3

Found on jsFiddle

let staff = { "name" : "Sarah",  // Primary member
                  "position"  : "Manager",
                  "years"       : 10 },

                { "name" : "Michael",  // Supportive member
                  "position"  : "Assistant",
                  "years"       : 5 }
                 ;
alert(staff);

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 reason behind the length property belonging to an array object?

While there are other instances, let's focus on the length property for now. Why does it appear as if we're copying it here: [].hasOwnProperty("length") //==> true It is common knowledge that an array's length property belongs ...

How can we achieve the same functionality as React Native's { flex: 1 } in React JS?

I've been diving into React Native development, and now I'm exploring React.js for web applications. However, I'm facing a challenge in creating a simple View that takes up the entire screen to begin experimenting with different components. ...

Is it possible to deserialize JSON with Jersey after it has been serialized?

Here is a snippet of code from a class named StatsResult: public class StatsResult { private final EditorUrlGenerator editorUrlGenerator; private final LiveMapUrlGenerator liveMapUrlGenerator; public String saveDate; public Map<Str ...

Having difficulty showcasing the JSON data within the dropdown list within an HTML table

In my HTML table, I have 4 rows with Order ID and Product Comments columns disabled. Users can enter data in other columns and submit it. Upon submission, I receive a JSON object which I iterate through and display in the table. I am facing two challenges ...

The Kafka control plane server experiences message validation failure on the broker side

I am facing an issue with message validation on a broker's side. I have executed the cp-server (simply ran cp-all-in-one compose file). created a new topic enabled confluent.value.schema.validation registered a JSON schema sent a message The validat ...

What level of trust can be placed in MUI Global Class names when using JSS?

Here is my current code snippet: const formControlStyles = { root: { '&:hover .MuiFormLabel-root': { } } } Would it be considered secure to utilize the class name in theme overrides for connecting with other components? Furthe ...

The exported JSON file from the editor is malfunctioning

After importing the obj file into the editor and exporting the geometry to a js file, I encountered an error in Firefox debug saying "Type Error: t1 is undefined". Interestingly, when I changed the model to the .js file exported by MaxExporter with both "E ...

Comparing front end automation between JavaScript and Java or Ruby

Could you provide some insights on why utilizing a JS framework like webdriverio is preferred for front end automation over using Selenium with popular languages like Java or Ruby? I understand that webdriverio and JS employ an asynchronous approach to fr ...

"Unleashing the Power of Spring Boot with JSON Many-to

Struggling with a coding issue... Currently working on my single page application using Spring Boot and Angularjs. Check out my users class below: @Entity @Table(name = "admins") public class Admin { @Id @GeneratedValue(strategy = GenerationTyp ...

Exploring the functionality of URLs in Node.js

I am working on testing an array of URLs to ensure that each one returns a 200 response code. So far, I have written the following code to accomplish this task. However, I have encountered an issue where only the last URL in the array is being tested. How ...

Tips on transforming json data into nested Maps with Gson

I have a custom Java class MyModel.java: public class MyModel { String name; int age; Details details; } In Details.java I have: public class Details { Info info1; Info info2; } In Info1.java and Info2.java, both have a common field called data ...

What are the specific files I should modify for HTML/CSS in my Ruby application?

My application was initially created with an introduction from: http://guides.rubyonrails.org/getting_started.html I am now looking to add some color and style through CSS. I have located the JavaScript and CSS files, but I am unsure which file is respons ...

Hot Module Replacement (HMR) for Redux Toolkit in React Native does not trigger updates in

TL;DR: Setting up the Redux Toolkit store in React Native for HMR correctly refreshes the app when changes are made, but the behavior of the reducer remains unchanged! Despite the announcement about React Native Reloading, it seems that the steps outlined ...

The outer DIV will envelop and grow taller in conjunction with the inner DIV

Could use a little help here. Thank you :) I'm having trouble figuring out how to get the outer div to wrap around the inner div and expand upwards with the content inside the inner editable div. The inner div should expand from bottom to top, and t ...

FullCalendar Angular 10 not displaying correct initial view

I am currently using Angular 10 along with FullCalendar version 5.3.1., and I am facing an issue where I cannot set the initial view of FullCalendar to day view. It seems to be stuck on the dayGridMonth view by default. Below is the HTML snippet: <full ...

React - utilizing dynamic properties using string values

I am facing a challenge in my test suite where I need to generate components with dynamic props. The desired components should look like this: <Button primary /> <Button secondary /> However, I am currently stuck at this point: [ &apos ...

The Selenium page_source method does not provide access to any changes made to the DOM tree

I am trying to analyze the impact of using addons like NoScript and Ghostery on a specific webpage. These addons are designed to block trackers' and advertisers' scripts, removing them from the DOM tree. For example, I tested the addon on a scrip ...

RestTemplate is unable to convert a JSON array into a Java object

Whenever I attempt to retrieve a list of values using RestTemplate, an error occurs. My setup includes Spring 3.0.0. The issue arises from: org.springframework.web.client.RestClientException: Error while extracting response for type [class [Lru.sandwichc ...

Tips on deleting a range of numbers in a list with jquery

I currently have the following layout: <ul id="ip-top-menu"> <li>Doesn't exclude</li> <li>Doesn't exclude</li> <li> <span>Doesn't exclude</span> <ul> ...

Encountered the dreaded "EXC_BAD_ACCESS" error in Thread 1 while working with Swift and iOS along with the HANDYJSON library

My app is crashing when trying to deserialize a struct after parsing JSON from the API. The issue started after updating xCode to Version 9.3 and I'm struggling to diagnose the problem or understand why it's happening. The crash occurs at this po ...