[英]Best way to change a value of a property. It's within an array of arrays of objects
[英]Best way to change a value of a property. It's within an object of an array of objects
當用戶單擊復選框時,我正在嘗試將selected
的值從當前的任何值(真或假)切換到相反的值。 我的toggleCheck
函數應該返回具有更改的選擇值的所有數據。 這是數據結構。 它是一個包含有對象的數組的對象。
{
"ModuleName": [{
"module": "string",
"selected": false,
"name": "title",
"points": [{
"category": "category1",
"description": "desc1",
"provided": "provided1"
},
{
"category": "category1",
"description": "desc",
"provided": "something"
}
]
},
{
"module": "string",
"selected": false,
"name": "title_one",
"points": [{
"category": "category1",
"description": "desc1",
"provided": "provided1"
},
{
"category": "category1",
"description": "desc",
"provided": "something"
}
]
}
],
[...],
[...]
}
我最接近的嘗試,但格式錯誤
function toggleCheck(checkedValue, valuesArr) {
return {
value: Object.entries(valuesArr).map(([key, values], i) =>
values.map((x) => {
return {
...x,
selected:
x.name === checkedValue.name ? !x.selected : x.selected,
};
})
),
};
}
可能是因為我使用了一個將其包裝在數組中的地圖
[
[
{},
{},
{}
],
[...],
[...]
]
^^^ 我得到了什么
{
"Name": [ {},
{},
{}
],
"Name": [...],
"Name": [...]
}
^^^ 我需要什么
function toggleCheck(checkedValue, valuesArr) {
//Step 0: Change the value in the data
let checked = Object.entries(valuesArr).map(([key, values], i) =>
values.map((x) => {
return {
...x,
selected:
x.name === checkedValue.name ? !x.selected : x.selected,
};
})
);
//Step 1: Group the modules into like arrays
let grouped = checked .flat().reduce(function (r, a, i) {
if (!i || r[r.length - 1][0].module !== a.module) {
return r.concat([[a]]);
}
r[r.length - 1].push(a);
return r;
}, []);
//Step 2: Assign the new object properties as the arrays.
//The key being the module name.
let newObj = {};
grouped.map((x, i) => {
newObj[x[0].module] = x;
});
return {value: newObj};
}
在您的問題中,您寫道:
{
"Name": [ {},
{},
{}
],
"Name": [...],
"Name": [...]
}
^^^ 我需要什么
this 不能存在於 JS 對象中。 只考慮 name 屬性的最后一次賦值,之前所有的只是這個屬性的舊值
編碼:
const data =
{ name:'aaa'
, name:'bbb'
, name:'ccc'
}
和編碼一樣
const data = {}
data.name = 'aaa'
data.name = 'bbb'
data.name = 'ccc'
證明:
const data = { name:'aaa' , name:'bbb' , name:'ccc' } console.log( data )
.as-console-wrapper {max-height: 100% !important;top: 0;} .as-console-row::after {display: none !important;}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.