![](/img/trans.png)
[英]How to update specific property by comparing two array of object in javascript?
[英]How to update the specific array element index position and specific array of object property in Javascript?
如何更新 Javascript 中的特定數組元素索引 position 和 object 屬性的特定數組? 我有以下基於 object 屬性的模擬數據需要使用擴展運算符更新它們各自的值。 我不能這樣做,因為它是嵌套的。
我可以使用以下方法來實現,但正如您所見,代碼行正在增加。 但是我們絕對可以減少使用傳播運算符。 因為在“標題”屬性中我只更新 0 索引,而在左列中只更新 label 值 rest 的東西是一樣的。
const mockData = {
title: ["Javascript", "Selected Topic"],
leftColumn: [
{
key: "name",
label: "Javascript Topic Name",
type: "string",
},
{
key: "id",
label: "Javasctipt Topic Id",
type: "string",
},
],
};
const handleType = (val) => {
switch (val.type) {
case "Javascript":
return {
...mockData,
};
case "Angular":
return {
...mockData,
title: ["Angular", "Selected Topic"],
leftColumn: [
{
key: "name",
label: "Angular Topic Name",
type: "string",
},
{
key: "id",
label: "Angular Topic Id",
type: "string",
},
],
};
case "React":
return {
...mockData,
title: ["React", "Selected Topic"],
leftColumn: [
{
key: "name",
label: "React Topic Name",
type: "string",
},
{
key: "id",
label: "Reacr Topic Id",
type: "string",
},
],
};
}
};
然后你可以這樣做:
const handleType = (val) => {
const newTitle = [val, ...mockData.title.slice(1)];
const newLeftColumn = mockData.leftColumn.map((arrValue) => {
const newLabel = arrValue.label.split(" ");
newLabel[0] = val;
return {
...arrValue,
label: newLabel.join(" "),
})
return {
title: newTitle,
leftColumn: newLeftColumn,
}
}
這就是您甚至可以將內容添加到 title 或 leftColumn 數組的方式,並且仍然可以正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.