修改嵌套数组里面的某个属性值

现在我有这样一个数组

[
    {
        "sectionVId":"1",
        "sectionName":"一等票",
        "season":[
            {
                "seasonVId":"1",
                "seasonName":"8点-12点",
                "ticket":[
                    {
                        "ticketVId":"1",
                        "ticketName":"儿童票",
                        "outerProductCode":"123456789"
                    },
                    {
                        "ticketVId":"2",
                        "ticketName":"儿童票",
                        "outerProductCode":"123456789"
                    },
                    {
                        "ticketVId":"3",
                        "ticketName":"老人票",
                        "outerProductCode":"1234567890"
                    }
                ]
            },
            {
                "seasonVId":"2",
                "seasonName":"12点-17点",
                "ticket":[
                    {
                        "ticketVId":"4",
                        "ticketName":"儿童票",
                        "outerProductCode":"123456789"
                    },
                    {
                        "ticketVId":"5",
                        "ticketName":"儿童票",
                        "outerProductCode":"123456789"
                    }
                ]
            }
        ]
    },
    {
        "sectionVId":"3",
        "sectionName":"三等票",
        "season":[
            {
                "seasonVId":"1",
                "seasonName":"8点-12点",
                "ticket":[
                    {
                        "ticketVId":"6",
                        "ticketName":"儿童票",
                        "outerProductCode":"123456789"
                    },
                    {
                        "ticketVId":"7",
                        "ticketName":"儿童票",
                        "outerProductCode":"123456789"
                    }
                ]
            }
        ]
    }
]

希望提供一个方法可以修改到outerProductCode的值。用遍历感觉有些不太好

阅读 2.3k
3 个回答

在所有数据中,如果outerProductCode都是一样的,则应该考虑在单独的地方放置这个吧。

    const arr = [];// 数据数组
    const ticket = [];
    for (let section of arr) {
      for (let season of section.season) {
        ticket = ticket.concat(season.ticket);// 提取ticket
      }
    }
    const arrObj = {};
    arr.forEach((item) => (arrObj[item.ticketVId] = item)); // 设置键对
    
    function changeCode(id, code) {
      arrObj[id].outerProductCode = code;
    }
 console.log(JSON.parse(JSON.stringify(data).replace(/(.+?outerProductCode":")(.+?)(")/g, (p0, p1, p2, p3) => p1 + "gogoing" + p3)));
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题