What is the best way to assign multiple values to a single key without replacing the existing value?

My goal is to store multiple values for a single key by utilizing arrays within my main object. I've been struggling with this and feeling discouraged, questioning why I thought I could accomplish it. Can someone provide guidance on the best approach to achieve this?

let mainObj = {}


const func = (str, obj) => {
  mainObj[str] = [obj]
}

func('str1', {content: 'content1' } )
func('str2', {content: 'content2' } )
func('str2', {content: 'content3' } )

console.log(mainObj)

//instead of this:
{ str1: [ { content: 'content1' } ],
  str2: [ { content: 'content3' } ] }


//I want this:
{ 
  str1: [ { content: 'content1' } ],
  str2: [ {content: 'content2' }, { content: 'content3' } ]
}

Answer №1

To create an array from it, simply follow these steps:

const newArray = (string, object) => {
  mainObject[string] = (mainObject[string] || []).concat([object])
}

Answer №2

It is important to verify if there already exists an array with the same string key before taking action;

If it does, you should append the new object to that existing array instead of replacing it entirely,

If not, proceed with creating a new array using that key.

let mainObj = {}

const func = (str, obj) => {
  if (mainObj[str]){
    mainObj[str].push(obj)
  }else{
    mainObj[str] = [obj]
  }
}

func('str1', {content: 'content1' } )
func('str2', {content: 'content2' } )
func('str2', {content: 'content3' } )

console.log(mainObj)

//Instead of replacing the array completely:

Answer №3

It's best practice to use the push method when adding elements to an existing object rather than overwriting it completely.

let data = {}

const updateData = (key, value) => {
  if (!data[key]) {
    data[key] = [];
  }
  data[key].push(value);
}

updateData('key1', {
  info: 'info1'
})
updateData('key2', {
  info: 'info2'
})
updateData('key2', {
  info: 'info3'
})

console.log(data)

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 best way to display hover-over text pop ups on menu list items in jsTreeR?

As a dedicated user of the jsTreeR package within Shiny, I have been exploring the functionality it offers. By executing the code below, users are presented with a draggable menu at the top, allowing them to drag items down to the designated list labeled " ...

Tips on gathering information from an HTML for:

After encountering countless programming obstacles, I believe that the solution to my current issue is likely a simple fix related to syntax. However, despite numerous attempts, I have been unable to resolve it thus far. I recently created a contact form ...

Bring in iPhone contacts into a table for easy viewing

After extensive research on the topic, I was looking for ways to import iOS contacts into a UITableViewController. The reason behind this is that my root view is a UITableViewController within a UINavigationController, and similar to WhatsApp, I named it ...

Exploring JSON parsing using javascript?

I'm currently attempting to work through this webRTC example and have encountered an issue that appears to be minor in nature... The if statement consistently fails to return true, despite the fact that the console message indicates that the property ...

Leaflet setStyle changes are effective when applied through the console but do not reflect in the actual

I currently have a map with around 1000 polygons that I am loading onto it. My goal is to color these polygons based on a specific property value. The code snippet below showcases my approach, but the results are not as expected. mapLayerFieldGrid = new L ...

Destructuring and For of Loop in ES6: Capturing the first object only

Working with my react app, I have a specific object called 'topics' that I am looping through: const topics = [ {name: 'Mon', color: 'blue', id: 1}, {name: 'Tue', color: 'red', id: 2}, {name: 'W ...

Creating a responsive form with live updating using ReactJS and utilizing double inputs for better

Currently, I am working on updating a form with double input fields. The aim is for users to be able to click an 'add' button and update the state with their values, while ensuring that the two input fields are "connected". To better illustrate m ...

Error: `THREE is not defined` was encountered in `app.js` on line 3524 when trying to load `three-bmfont-text/index.js`

My goal is to utilize Three.js along with three-bmfont-text in order to generate 3D text and enhance its appearance using shaders. After installing three and three-bmfont-text via npm, I imported them into my JS file: import * as THREE from 'three&a ...

Why is the button missing from the codepen?

I attempted to recreate the code from this Codepen link: https://codepen.io/jakaric/pen/mjJQvg However, unlike what you see here (in the run result), the liquid "Pretty little button" is not showing up in my local files. On Codepen, there is no library me ...

Is there a button that doesn't trigger a postback action?

I encountered an issue on my asp.net page where a button triggers a JavaScript function, but after the script runs, the page reloads (postback). How can I prevent this from happening? <button onclick="printElement('content');">Print</bu ...

Steps for adding a variable to a JSON request

I'm new to JavaScript and React Native and I'm looking for a way to include variables in a JSON request. Specifically, when making a JSON request using Fetch or Axios to a URL, I need to customize the URL based on certain parameters. For instance ...

Is there a way for me to handle state changes within a controller for nested views?

Currently, I am attempting to execute a resolve function upon a state change in order to retrieve data that I need to inject into a controller that utilizes "multiple" views. The rationale behind having nested views is due to the presence of a template/app ...

What is the best way to access the rendered child components within a parent component?

I am seeking a way to retrieve only the visible child components within a parent component. Below is my unsuccessful pseudo-code attempt: parent.component.html <parent (click)="changeVisibility()"> <child *ngIf="visible1"></child> ...

Building a Backbone Model by utilizing JSON information that was received

Is there a way to create a backbone model using data received from a web service, rather than manually inputting the information? Imagine you're getting JSON data from a webservice, and you'd like to directly use this JSON as a backbone model. H ...

What methods can I use to modify strings within JSX?

Within a JSX file, I am faced with the task of manipulating a particular string in a specific manner: Imagine that I have the following string assigned to medical_specialty = "Plastic Surgery" The objective is as follows: medical_specialty.replace(&apos ...

JavaScript - Unable to Modify Select Value with Event Listener

It's interesting how I can change the selected option in a dropdown list using JavaScript without any issues. However, when I try to do the same thing within an event listener, the option does not seem to change. Here's the HTML code: <select ...

Avoid changing the format when sending a JSON string to Node

I am attempting to send JSON data to a Node application using a POST request, which will then be retrieved through a GET request. On the client side, I create a JSON string representing the model and send it to the server: $.post(serverURL, ko.mapping.toJ ...

Rendering the Next.js Link tag on the page is displaying as [object Object]

Hey there! I'm currently working on creating breadcrumbs for a webpage and this is what the breadcrumb array looks like: const breadcrumbs = ['Home', "Men's Top", 'Winter Jacket'] Now, in JSX with Next.js, I am att ...

Using a conditional statement to wrap a react Route

Currently, I am facing a challenge while working with react router. Initially, I had two distinct components being rendered under the same route - one with a parameter and one without (this was how the routes were distinguished). Now, my goal is to add opt ...

"Enhance your Angular configuration with the powerful ngBootbox plugin

Is there a way to permanently change the locale of ngBootbox? I tried adding an extra angular configuration: var app = angular.module('some_module', ['highcharts-ng', 'ui.router', 'oc.lazyLoad', 'ui.selec ...