What is the best way to insert a list into an object without overwriting the existing content under the relevant keys?

Having transitioned from PHP to JavaScript, I am struggling with performing simple tasks involving associative arrays in JS that I could easily do in PHP. It seems like my approach might not be the best fit for this language.

Currently, I have an object that needs to be rebuilt for future purposes, with new information being added during a while cycle.

Let's consider the following initial data:

array[0] = { company: 'kfc', position: 'chicken', name: 'Andrejs', age: '20 days' }

array[1] = { company: 'kfc', position: 'chicken', name: 'Alex', age: '15 days' }

array[2] = { company: 'mcdonalds', position: 'chicken', name: 'Lena', age: '23 days' }

The desired output should look like this:

{
 {kfc: 
  {chicken: 
   {name: "Alex", Age: "15 days"}, 
   {name: "Andrejs", Age: "20 days"}
  }
 }, 
 {mcdonalds: 
  { chicken: 
   {name: "Lena", age: 23 days}
  }
 }
}

I have attempted the following solutions:

  1. Create an object: food = {};
  2. To generate the object within a while loop:
food[m] = {array[i].company : {array[i].position : {name: array[i].name, age: array[i].age}}}
m++;

However, this approach failed because it resulted in separate strings within the object. 4. Attempting to use keys before the = sign:

food[array[i].company][array[i].position] = {name: array[i].name, age: array[i].age}

This led to an error due to non-existent keys during the first iteration.

I have reviewed various object tutorials but have yet to find a solution. I would greatly appreciate guidance on the correct way to create associative objects in JavaScript.

Answer №1

To achieve the desired result, one can utilize the Array.reduce() method while grouping based on the keys `company` and `position`.

During iteration, we verify if there are any existing entries for each key; otherwise, new entries are created.

The `position` property in the output will store an array of all entries related to that specific position.

    

let arr = [
    { company: 'kfc', position: 'chicken', name: 'Andrejs', age: '20 days' },
    { company: 'kfc', position: 'chicken', name: 'Alex', age: '15 days' },
    { company: 'mcdonalds', position: 'chicken', name: 'Lena', age: '23 days' }
];

const output = arr.reduce((acc, { company, position, age, name }) => { 
    // If no existing items are here, create an empty object for this company.
    acc[company] = acc[company] || { };
    // If no existing items are here, create an empty array for this position. 
    acc[company][position] = acc[company][position] || [];
    // Add the entry for the relevant position
    acc[company][position].push({ age, name})
    return acc;
}, {})

console.log(output)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Check out this neat groupEmployees function that beautifully structures an array of employees into a hierarchical object:

Try it in TS Playground

function groupEmployees (employees) {
  const organized = {};
  for (const { age, company, name, position } of employees) {
      ((organized[company] ??= {})[position] ??= []).push({ age, name });
  }
  return organized;
}

const employees = [
  { company: 'kfc', position: 'chicken', name: 'Andrejs', age: '20 days' },
  { company: 'kfc', position: 'chicken', name: 'Alex', age: '15 days' },
  { company: 'mcdonalds', position: 'chicken', name: 'Lena', age: '23 days' },
];

console.log(groupEmployees(employees));

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

Customize Highcharts axis properties after adding additional series to the plot

When working with highcharts, I utilize the xAxys and yAxis properties to format the inserted data. The code used is the same for both axes, so I'll provide an example for one of them: $('#containers').highcharts({ .... .... yAxis: { ...

Error: Node application using Express does not display 'Server Started' message in console upon execution

I'm encountering an issue where I don't see the "Server Start: 3001" message on the console when I run 'node app.js' in the terminal. Below is the content of my app.js file: var createError = require('http-errors'); var exp ...

Looking to send a user elsewhere if there are no errors present in the javascript errors tag

Looking for a way to redirect users to another page if the #errors are empty. Any advice on how to achieve this successfully? I attempted using an if statement but it didn't work out as expected. $(document).ready(function(){ $( ...

Utilize the value of one variable to determine access to another variable in Javascript

I am working with several boolean variables and I want to create a new variable that keeps track of the most recently changed boolean variable. This way, every time a new boolean variable is modified, I can toggle the previous one. If you have any ideas o ...

accessing elements of an octave matrix with a different array

Hey there, I'm working with a three-dimensional octave array called A that has the size [x y z]. Additionally, I have another array B with dimensions n * 3. Let's say B(0) gives me [3 3 1]. I want to access that specific location in array A, m ...

Continue the conversation as you scroll down in the chatbox

Struggling to implement an automatic scroll to the bottom of a chat window when a new message appears. HTML: <div class="content chat-body" id="messages"> <div class="chat-message" v-for="message in messages"> <p class="title i ...

Steps to trigger a JavaScript popup from an iframe window to the parent window

Currently I am developing a web application using JSP with JavaScript. Within the parent window, an iframe is being utilized. The issue arises when a button in the iframe page is clicked, as it opens a popup window within the iframe itself. However, my obj ...

jQuery UI Autocomplete for web addresses

I am trying to implement instant search with jQuery UI autocomplete, and I want to be able to add a link that will be triggered when a result is clicked. Javascript $("#searchinput").autocomplete({ source: "search/get_searchdata", select:function ...

Tips for fixing the issue of array.map not being a function in React

I am currently attempting to map an array within a functional component. The array is stored as state and its values are generated within the same component. Here is a summary of my approach: import React, { useState , useEffect } from 'react&apos ...

Interactable elements on a spherical map in three.js

I've been trying to implement raycasting to make objects clickable. Despite referencing numerous examples, the code doesn't seem to work for me. The only notable difference is that I'm working within a sphere. My initial setup involves defi ...

ReactJS encountering problem with checkbox filtering functionality

I am facing a challenge troubleshooting the checkbox filtering problem as I am relatively new to ReactJS. The code I'm using is based on an online reference, which I modified to suit my needs. However, due to my limited knowledge, I need assistance wi ...

establish expiration date for image

On my e-commerce site, users upload images to customize product items, such as adding their photo to a cake. I'm curious if there's a way to automatically delete these images after a certain expiry date. Is it possible to implement an automatic ...

Is there a way to store data in a variable for caching in NextJS?

After receiving JSON data from an online API, I am looking for a way to store and cache the response for the duration of my application running. Is there a method to accomplish this in Next.js without relying on an external library for such a basic task? ...

Utilizing Django Data for Dynamic Google Charts

Observation: def view_page(request, template = 'home.html'): if request.user.is_authenticated(): data = [['jan'],[12],[-12]] context = { 'data' : data, } return render( request, te ...

A Comparison of Mootools Elements in Moo Versions 1.1 and 1.2

I have a script that uses mootools 1.1 to manage an Ajax "form" and checks how many rows are in the dynamically created form before processing them: form_rows = $$('#form_row'); // The number of rows can vary from 4 to 20 console.log(form_rows.l ...

Retrieve the CSS selector for the element that my plugin has been implemented on

Currently, I am in the process of developing a jQuery Plugin that is designed to be applied on a specific container element like so. $('#container').myPlugin(); Within this plugin, my goal is to retrieve the same element from another page using ...

Investigating Event Bubbling in Chrome's JavaScript

I created an HTML document that contains several div elements: <div id='divTop'> <div id='divChild'></div> </div> At the end of the document, I added the following JavaScript code: var top = document.getEl ...

Error occurred during parsing of mapping in elasticsearch while using node.js

My journey with elasticsearch is just beginning. I am currently working on implementing elasticsearch in my node.js(express) project. Inside my elasticsearch.js file, there are two important functions: /** Function to map data for storage in elastic searc ...

Why is my Java Object Array throwing an InputMismatchException?

Having trouble with InputMismatchException while entering values at runtime. Check out the attached code and exception snapshot for more context. import java.util.Scanner; class ObjectArray { public static void main(String args[]) { Scann ...

Obtain item from JSON data structure

After querying my database, I receive a JSON object with the following structure: items = [ {"ID":1, "CODE":"code1", "DESCRIPTION":"abcd", "PRICE":100}, {"ID":2, "CODE":"code2", "DESCRIPTION":"efgh", "PRICE":100}, {"ID":3, "CODE":"code3", "DES ...