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

The authentication function is not functioning properly within the controller when transitioning from Vue

In my controller, there is a store method where I am inserting the auth()->user()->id for a field. It works fine when submitting the form from a regular blade template, but it returns a 500 error when submitting from a Vue component. However, if I use st ...

Navigating through each element of an array individually by using the onClick function in React

I'm currently working on a project that involves creating a button to cycle through different themes when pressed. The goal is for the button to display each theme in sequence and loop back to the beginning after reaching the last one. I've imple ...

Trigger is not activated by dynamically created element

I am dealing with a block of code that is dynamic and looks like this. var li3 = document.createElement('li'); li3.classList.add("col-sm-3"); li3.classList.add("no_padding"); var inner = ""; inner = inner ...

Guide on how to add multiple options to a select element in HTML using prototype.js

What is the best way to add multiple options to a select tag in HTML using prototype js? Appreciate your help. ...

What is the process for appending a file extension to a Next.js URL?

For instance, I am attempting to redirect the URL : https://example.com/data/publications to this : https://example.com/data/publications.json I made an attempt using Next.js redirection, but encountered difficulty when trying to add a string that does no ...

Troubleshoot: Why is my Google Chrome not playing videos? Uncover the solution with a

I have created a webpage with an HTML video tag that loads dynamically from a JSON file. I am currently using Chrome 50 for this project. The response is successful, and when inspecting the page using Chrome's developer tools, I can see the video tag ...

What is the best way to pass an array of 8-digit strings from an input in Angular to a Node.js backend?

I am currently facing a challenge where I need to pass an array of 8 digit strings from an Angular input to a Node.js endpoint. The method below works perfectly fine when passing a single string, but how can I handle an array of 8 digit strings as input? ...

Is there a way to extract both a and b from the array?

I just started learning programming and I'm currently working on creating an API call to use in another function. However, I've hit a roadblock. I need to extract values for variables a and b separately from the response of this API call: import ...

"Improprove your website's user experience by implementing Material UI Autocomplete with the

Recently, I experimented with the Autocomplete feature in Material UI. The focus was on adding an option when entering a new value. You can check out the demo by clicking on this link: https://codesandbox.io/s/material-demo-forked-lgeju?file=/demo.js One t ...

triggering a function from a child component in React

I am facing a challenge in calling a function from the parent component that is stored in a child component. I understand how to do it from child to parent using props, but unsure about how to achieve it from parent to child. In the example below, you can ...

A table featuring an HTML select element that allows users to choose from preset options or manually enter

My goal is to incorporate a select box where users can either choose from a set list of options or input their own custom value. The select element is nested within a table. Unfortunately, using datalist is not a viable solution for me in this case. I have ...

What steps can I take to allow a third-party JavaScript to access my TypeScript object?

I am working on an Angular application and I have a requirement to develop an API for a third-party JavaScript that will be injected dynamically. public class MyApi{ public callSomeFunction():void{...} public getSomeValue():any {...} } var publicA ...

Issue with jqGrid Multiple Selection

When constructing my jqgrid, I utilize the following code: multiselect: true This enables a check all column. However, clicking the check all checkbox (located at the header) selects all checkboxes, but does not click the checkboxes in each row. You can ...

using the information from the child array within a v-if condition

I'm struggling to extract data from a child array and utilize it in my v-if condition. Below are my data and code. Any assistance would be appreciated, even if it's just pointers to the right documentation. <div class='post' v-for= ...

Customize Text Area's Font Based on Selected Option in Dropdown List

I'm currently working on an HTML file that includes a dropdown list and a text area. Here's the code snippet: <select id='ddlViewBy' name='ddlViewBy' onchange='applyfonttotextarea()'> <option value = ' ...

Tips for closing the navbar by clicking elsewhere on the page

Is there a way to modify my code in order for the navbar to close when clicking outside of it, while staying open if something inside it is clicked? $(document).ready(function() { $('.nav-btn').on('click', function() { $('.na ...

Difficulty in transmitting two boolean values using ajax and setTimeout()

I am working on two functions that are supposed to send either 0 or 1 to a PHP page using AJAX. When a key is pressed on the keyboard, the function that sends 1 should start, followed by the second function that sends 0 three seconds later using setTimeout ...

Remove identical options from the dropdown menu

After hard-coding and adding items to the dropdown list for team size, such as 1, 2, 3, I am encountering an issue when loading it for editing or updating. Duplicate values are appearing in the list: 1 1 2 3 4... How can I remove these duplicate value ...

Is Angular File API Support Compatible with HTML5?

When checking for HTML5 File API browser support in my code: private hasHtml5FileApiSupport; constructor(@Optional() @Inject(DOCUMENT) document: Document) { const w = document.defaultView; this.hasHtml5FileApiSupport = w.File && w.FileReader & ...

Issue with mouse movement in Selenium and Protractor not functioning as expected

Greetings! I am currently facing an issue in my Angular application with Openlayers3 map integration. There is a layer representing a building on the map, and when I try to click on a building during testing, it should trigger a side panel displaying image ...