Modifying an element within a nested array

I am struggling to create a JavaScript function that can update the "checked" value within an object in an array structured as follows:

array:[
  { id:1,
    name:"foo",
    options: [
      {id:"one", checked: false},
      {id:"two", checked: true}
    ]
  },
  { id:2,
    name:"faa",
    options: [
      {id:"one", checked: false},
      {id:"two", checked: true}
    ]
  }
 ]

I have experience with updating the values in an array of objects, but I'm unsure how to approach this specific structure. Any advice or suggestions would be greatly appreciated.

Please note the typo correction in the array format.

Answer №1

It seems like you are looking to make updates to the checked property using checkboxes in an HTML template.

Check out this demo :

new Vue({
  el: '#app',
  data: {
    array: [{
        id:1,
        name:"foo",
        options: [
        {id:"one", checked: false},
        {id:"two", checked: true}]
    }, {
        id:2,
        name:"faa",
        options: [
        {id:"one", checked: false},
        {id:"two", checked: true}]
    }]
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="data in array" :key="data.id">
    <b>{{ data.name }}</b>
    <div v-for="(checkboxData, index) in data.options" :key="index">
      {{ checkboxData.id }} : <input type="checkbox" v-model="checkboxData.checked"/>
    </div>
  </div><br>
  <b>Updated Value : </b>
  <p>{{ array }}</p>
</div>

Answer №2

To generate a new array of objects with the updated values, you can utilize the map() method.

const info = [{
    id: 1,
    name: "foo",
    options: [
      { id: "one", checked: false },
      { id: "two", checked: true }
    ]
  },
  {
    id: 2,
    name: "faa",
    options: [
      { id: "one", checked: false },
      { id: "two", checked: true }
    ]
  }
];

const modifiedResult = info.map((i) => {
  return {
    ...i,
    options: i.options.map((x) => {
      return {
        ...x,
        checked: !x.checked // invert the checked value as an example
      }
    })
  }
});

console.log(modifiedResult);

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

How can JavaScript be used to prevent pinch and zoom functionality on Google Maps?

In my project, I am utilizing Google Maps but I want to disable the zooming effect on the map. To achieve this, I have disabled the zoom control using zoomControl: false,. However, this modification only applies to desktops and laptops as they do not suppo ...

Comparing DOM Manipulation and Templating

Currently in the process of enhancing the performance of my HTML5 phonegap application, I am faced with the challenge of efficiently managing a <ul> element that is frequently updated. For the initial injection of database data, I am utilizing Docum ...

Issue with utilizing Vuejs variable in Google Maps Matrix API function

Having trouble accessing a Vue.js variable in a function using the Google Maps Matrix API. I am trying to use the Google Distance Matrix API to calculate the distance between two locations. I have declared a variable globally and changed it within a functi ...

What measures can I take to restrict users from adding names that are already in the system?

In the handleSubmit() function, I am attempting to prevent the user from adding an existing user, but it doesn't seem to be functioning properly. Ideally, if the name being added already exists in the persons list, an alert should be triggered. EDIT: ...

What is the reason behind the increasing popularity of single quotes in JavaScript files in recent times?

What is the reason behind the increasing trend of using single quotes ' instead of double quotes " around string in JavaScript? Are there minification or linting tools that adhere to the convention of using double quotes for strings and single quotes ...

Tips for implementing orderBy and filter in ng-repeat when working with an object instead of an array

I am facing a data structure that looks like this: $scope.people = { "ID123": { name_de: "Andre", name_en: "Anrew", age: 30, description: "He is the father of xyz and . . .", . . . ...

Submitting JSON data using Alamofire in Swift

How do I send an array of JSON objects using Alamofire in Swift? The data I need to post is as follows: dataArray = [{ "time": 1, "score": 20, "status": true, "answer": 456 }, { "time": 0, "score": ...

Creating a custom navigation bar that elegantly fades away with a smooth animation as you scroll down the page is a must-have

How can I create a navigation bar that disappears when scrolling, with a smooth animation? This is the progress I have made so far. HTML: <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="css/style.css" type="tex ...

What is the best way to display individual array items in Python without including square brackets around them?

Is there a way to display the list elements in the second loop without having square brackets around them when running the program? room_lengths=[] room_widths=[] areas=[] print("House floor area calculator") rooms=int(input("How many rooms are there? " ...

Experience the convenience of running Javascript code directly within the editor of Intellij IDEA

After spending a lot of time writing code in the Ultimate edition of Intellij Idea, I find myself frequently needing to test methods or large code sections. I often find myself copying and pasting code into Firebug in Firefox, which is a small and cramped ...

Limitations exist when trying to open multiple tabs using the same link in Express puppeteer

Update: I found that changing "networkidle0" to "networkidle2" fixed the issue. Special thanks to vsemozhebuty for their helpful comment on this topic. I'm currently working on a web scraping project using Express and puppeteer. The following code sn ...

What is the best way to substitute multiple characters at a specific position in JavaScript?

I'm struggling to figure out how to replace more than one character at a specific index in a string. I attempted using a FOR loop, but it didn't yield the desired results. String.prototype.replaceAt=function(index, replacement) { return this ...

Combining Python Arrays with JavaScript Indexing in Django's Template Language

Hey there, I have a question that's been bugging me for a while. While working on rendering a view in Django, the python side of my code looks something like this: ... marray = [1, 2, 3, 4, 5] ... return render(request, "template.html", {"marray": ma ...

Instead of just displaying a count after updating in the database, the updated object will be

Updating an entry in a food truck database requires some adjustments. Here is the model function for handling updates: function updateTruckInfo(changes, id) { return db('trucks') .where({ id }) .update(changes) .then( ...

Tips for testing nested HTTP calls in unit tests

I am currently in the process of unit testing a function that looks like this: async fetchGreatHouseByName(name: string) { const [house] = await this.httpGetHouseByName(name); const currentLord = house.currentLord ? house.currentLord : '957'; ...

the dropdown menu toggle is not working as expected

My dropdown icon is not appearing and the menu options are not functioning properly. Despite trying to use a script to display the text when an option is clicked, it doesn't seem to be working. It appears that the toggle functionality is not working ...

JasmineJS: manipulating the DOM to achieve the desired outcome

Currently, I am in the process of writing unit tests for a function that requires fetching values from the DOM for processing. getProducts: function() { //Creating query data var queryData = {}; var location = this.$('#location').val(); ...

Constructing the necessary gulp configuration file

When using Gulp and Gulp-sass, with the use of 'gulp.watch', how can I retrieve the directory name of the modified item on the watchlist in order to compile the sass to css? Currently, the setup only compiles the sass files from theme 1. If ther ...

Why doesn't the Iframe onLoad event trigger when uploading a file?

I have a straightforward iframe <iframe class="ifr" src="about:blank"></iframe> It contains an onload handler. $(".ifr").on('load',function (){ alert("iframe loaded") }); There are also two buttons: Pressing the first button ...

Execute protractor to open chrome in incognito mode and disable web security for cross-origin resource sharing

Our application performs well in production with CORS enabled. I am working on a project that is not CORS-enabled locally. Is there a way to disable web security for protractor? Can I modify the selenium instance by adding arguments? We are interested in ...