Populate an array of objects with various key-value pairs

In my @change method, I receive the following values:

 changeAttr(id, key, value) {
  const selections = [];
},

id can be any number, key could be: color, size, sex, etc..., and value could be: red, 8, female, etc. Initially, the values might look like this: id = 3, key = "color", value = "red". These values change when the user selects another option, for instance: id = 3, key = "sex", value = "female" or id = 5, key = "size", value = "50" ...etc

The goal is to dynamically populate an array of objects with these values as shown below:

selections = [{
              "3": { 
                  "color": "red",
                  "sex": "male",
                  "size": "40" 
              },
              {
          ...
               }];

If a key already exists for the same id in the array, I want to overwrite its value. If it doesn't exist, I want to add it for that particular id.

I hope this explanation is clear. Thank you for your time!

Answer №1

If you want to define properties in JavaScript, you can use array syntax like this:

For example,

let yourObject = {}

To define a property, you can use [] brackets

yourObject["color"] = "red"

Following the same logic, you can do:

yourObject[key] = value

A tip: It is not recommended to use integer strings as indexes because JavaScript reindexes arrays. It is better to construct your object in a structured way:

[
  {
    id: 3,
    color: "red",
    sex: "male",
    size: "40" 
  },
  {
    id: 5,
    color: "black",
    sex: "female",
    size: "36" 
  },
  {
    id: 8,
    color: "black",
    sex: "female",
    size: "36" 
  },
  ...
];

EDIT :

const selections = [];

function changeAttr(id, key, value) {
   
  // Get the index in selection by id
  let index = selections.map(t=>t.id).indexOf(id)
  
  
  if (index !== - 1) { // if the id have been found
  
      selections[index][key] = value // It create the index "key" if not found, and replace the value if found 
  
  } else { // if the id have not been found
    
    let tmp = {
      id: id
    }
    
    tmp[key] = value
    selections.push(tmp)
    
  } 
}

console.log(selections)
changeAttr(6, "color", "red")
console.log(selections)
changeAttr(3, "sex", "female")
console.log(selections)
changeAttr(6, "sex", "male")
console.log(selections)
changeAttr(6, "color", "yellow")
console.log(selections)

You can run snippet to see, I believe this is what you are searching for

Answer №2

updatedValue =  { 
  "color": "blue",
  "gender": "male",
  "size": "42" 
 }


choices.forEach((item)=>{
  for(let property in item){
    if(item.hasOwnProterty(property)){
       // update existing value
    }else {
      // set the updatedValue 
    }
  }
})

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

React - z-index issue persists

My React App with Autocomplete feature is almost complete, but I need some assistance to double-check my code. https://i.stack.imgur.com/dhmck.png In the code snippet below, I have added a search box with the className "autocomplete" style. The issue I a ...

What does drizzle.config.ts serve?

I've been working on setting up a project with Drizzle + Next.js + Vercel for my serverless backend. To utilize the ORM API of Drizzle, I reference my database in the following way: import { drizzle } from "drizzle-orm/vercel-postgres"; impo ...

Can you explain the distinction between employing express.urlencoded() with extended set to true as opposed to setting it to false along with performing manual JSON stringify/parse calls?

Within my NodeJS/Express server, I am faced with the decision of setting extended to either true or false for the urlencoded middleware: app.use(express.urlencoded({ extended: true/false })); I have come to understand that when set to false, it signifies ...

Leveraging an HTML interface in conjunction with a node.js application

My objective is to implement JavaScript on the server side. To achieve this, I have decided to use node.js as it seems like the most logical solution. While I am quite familiar with node.js from working on applications, I now need to utilize it for server- ...

How can Swipe support help you slide a menu back in?

For implementing swipe support on my landing page carousel, I included jquery.mobile.custom.min.js. However, I am facing a challenge with adding swipe support to "close" the menu. Essentially, swiping left should have the same effect as clicking the butto ...

Locating elements with Selenium Webdriver using xpath

<a style="color:White;" href="javascript:__doPostBack('dnn$ctr674$Case$gvCaseSearchDetails','Page$777')">777</a> Can anyone help with writing an xpath for the HTML code above? The goal is to locate elements using the identi ...

The function 'fileURLToPath' cannot be found in the __vite-browser-external export

Encountering a build error while using Nuxt 3.0 stable version. nuxi dev works without any issues. However, when I run nuxi build, the following error is displayed: ERROR 'fileURLToPath' is not exported by __vite-browser-external, imported by ...

Unleashing the power of Sinon: a guide to covertly observing the e

I need to verify if the method "res.render" is invoked with the correct parameters. it("Checks if the page for creating a new user is rendered", done => { const spy = sinon.spy(ejs, "render"); chai .request(app) .get("/users/create ...

Utilize a vanilla JavaScript object as the primary model in Ember

Can a plain JS object, such as a literal object, be used as a model in EmberJS? I've noticed that all the examples in the documentation utilize Ember.Object or a datastore. I understand that I may not have access to features like observables with pl ...

The toggle function for the classList ('open') is functioning correctly and can be seen in the inspect element tool, however, the website is not displaying the associated style

How can I make the .nav show styles in .open after clicking #menu-icon? Note: I used Bootstrap to create the nav HTML <!-- logo --> <div class="logo"> <img src="assets/logo.png" alt="logo g's shop& ...

What is the best way to ensure the network is idle after clicking on an element in puppeteer?

Is there a way to wait for network idle after clicking on an element in puppeteer? const browser = await puppeteer.launch({headless: false}); await page.goto(url, {waitUntil: 'networkidle'}); await page.click('.to_cart'); //Clicking o ...

The React class component is throwing an unexpected error with the keyword 'this'

I encountered an error stating "Unexpected keyword 'this'" while attempting to update the React state using Redux saga. Could someone shed light on what's wrong with the code below and how I can fix it? class Welcome extends React.Component ...

Unable to adjust the padding of a div while the Bootstrap 4 navbar is in a collapsed state on mobile devices

I am facing an issue with a fixed navbar at the top of my page. Below the navbar, I have the page content which includes a Bootstrap 4 image carousel. The problem arises on mobile devices where I need to add top-padding to the page-container (below the nav ...

Leverage the power of PHP files within your JavaScript code

I have a PHP file with some calculations that I want to integrate into another JavaScript file. How can I pass variables from JavaScript to perform calculations inside the PHP file? Here is my JavaScript code: $("#upload").on("click", function(){ var ...

I am eager to create a Material-UI textfield using an array

My current task involves utilizing TextField based on an Array, but I am facing an issue with dynamically changing all the values. I understand that I can employ ternary conditions to accomplish this task effectively. const TextField = () => { r ...

What is the best way to showcase data in a table using React Js?

I'm working on a project in React Js where I need to display data fetched from an API in a table. The challenge is that the data is received as an object and I'm struggling to map through it efficiently. Currently, I have hardcoded some sample da ...

The package.json file is missing the "exports" main, causing the Error [ERR_PACKAGE_PATH_NOT_EXPORTED] to be displayed

Can anyone help me resolve the 'Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in package.json' issue? I've been struggling to fix it despite receiving assistance. The problem is quite baffling and the more I dwel ...

Improving the way text entered in an input box is displayed using HTML table cells

Seeking advice on how to display the last two input boxes in a dynamic HTML table so that users can easily view the data they have entered. The issue arises when the length of the data in these columns is large, making it difficult for users to see all the ...

Utilizing Mirth Connect to insert XML data into a MySQL database using JavaScript

I am completely new to working with Mirth, JavaScript, and MySQL. I have successfully set up a channel in Mirth to read a text file and convert it to XML. Everything is functioning properly so far. I also attempted to send the XML data to a MySQL databas ...

Arrow function returns itself, not the function

While working with React, I've been using utility functions for managing API calls. I noticed that when the arrow function is no longer anonymous, it successfully returns a pending promise – which is exactly what I want. However, if the arrow functi ...