I can't figure out how to make a javascript function to update the "checked" value inside the object in an array like this
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 know how to do it with array of objects but am stuck with this. Any suggestions into what I need to do? Thanks
Update typo in array format
CodePudding user response:
If I understand your requirement correctly. you want to update the checked
property via checkbox in HTML template.
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>
CodePudding user response:
what you have there is not a valid json Array i guess u want to edit is this 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
}
]
}
]
CodePudding user response:
You could use map()
to create a new array of objects with the updated values.
const data = [{
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 result = data.map((d) => {
return {
...d,
options: d.options.map((o) => {
return {
...o,
checked: !o.checked // for example invert the checked value
}
})
}
});
console.log(result);