美文网首页
JavaScript 根据路径查找对象中的某个属性,并更改该属

JavaScript 根据路径查找对象中的某个属性,并更改该属

作者: Rising_life | 来源:发表于2020-08-12 09:39 被阅读0次

    原对象

     let obj1 = {
          data: [
            {
              news_id: 51182,
              title:
                "Teslamask's American Business Relations: The government does not pay billions to build factories",
              source: "AI Finance",
              members: [
                {
                  title: [
                    {
                      news_id: 51184,
                      title:
                        "iPhone X Review: Innovative future with real black technology",
                      source: "Netease phone",
                    },
                  ],
                },
              ],
            },
          ],
        }; //原对象
    

    根据路径修改某个属性值 函数

        /*
         * objectStr 字符串格式 顶层数据层级名称
         * path 属性的路径
         * val 要改成的值
         */
        function findMod(objectStr, path, val) {
          let props = path.split(".");
          let th = "";
          for (let i = 0; i < props.length; i++) {
            th += "['" + props[i] + "']";
          }
          //判断是对象还是字符串
          let isObj = new Function("return " + objectStr + th);
          let e = new Function();
          if (typeof isObj() == "object") {
            e = new Function(objectStr + th + "=" + val);
          } else if (typeof isObj() == "string") {
            e = new Function(objectStr + th + '="' + val + '"');
          }
          e();
        }
    

    函数调用

    根据路径修改一个字符串属性值
        findMod(
          "obj1",
          "data.0.members.0.title.0.title",
          "根据路径修改一个属性值(字符串)"
        );
        console.log(obj1);
        document.write(obj1["data"]["0"]["members"]["0"]["title"]["0"]["title"]);
    
    根据路径修改一个字符串属性值
    根据路径修改一个对象属性值
    findMod("obj1", "data.0.members.0.title", '[{"a":"hhh"},{"a":"888"}]'); //修改一个子对象
        console.log(obj1);
    
    根据路径修改一个对象属性值

    相关文章

      网友评论

          本文标题:JavaScript 根据路径查找对象中的某个属性,并更改该属

          本文链接:https://www.haomeiwen.com/subject/fuvedktx.html