[英]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.