给json中动态添加多个键值对,以及如何获取json对象中的key

一,给json中动态添加多个键值对


给数组中的每一个json对象动态添加n个键值对
        let jsonArray = [
          {
            name: "张三"
          },
          {
            name: "李四"
          },
          {
            name: "王五"
          }
        ];
        let indexCodeLists = [
          {
            age: "12"
          },
          {
            age: "16"
          }
        ];
        for (let rt = 0; rt < jsonArray .length; rt++) {
          for (let g = 0; g < indexCodeLists.length; g++) {
            jsonArray [rt][`DatumName${g}`] = indexCodeLists[g].age;
          }
        }
console.log(jsonArray);--------------------------------->
      jsonArray = [
          {
            name: "张三",
           DatumName0:"12",
           DatumName1:"16",
          },
          {
            name: "李四",
           DatumName0:"12",
           DatumName1:"16",
          },
          {
            name: "王五",
           DatumName0:"12",
           DatumName1:"16",
          }
        ];

二,获取json对象的key和value

let filterJson  = {
    name:"张三",
   age:"12",
   sex:"男"
};
     for (var key in filterJson) {
           console.log(key); //获取key值
           console.log(json[key]); //获取对应的value值
        }

你可能感兴趣的:(给json中动态添加多个键值对,以及如何获取json对象中的key)