修改json对象并保存

时间:2017-10-12 19:20:57

标签: javascript arrays json

我有一个json数组对象。我需要修改它然后将修改后的版本保存在变量上。

json对象

var json = [ 
{ 
  "Name": "March-2016", 
  "Elements": [ 
    { 
      "Name": "aa", 
      "Elements": [ 
        { 
         "Name": "ss", 
          "Data": { 
            "Test1": [ 
              22
            ], 
            "Test2": [ 
              33 
            ],
            "Test3": [ 
              44
            ],
            "Test4": [ 
              55
            ]
          } 
        },
        { 
          "Name": "ssee", 
           "Data": { 
             "Test12": [ 
               222
             ], 
             "Test22": [ 
               3322 
             ],
             "Test32": [ 
               445
             ],
             "Test42": [ 
               553
             ]
           } 
         }  
      ] 
    } 
  ] 
} 

];

需要修改为

 var json = [ 
{ 
  "Name": "March-2016", 
  "Elements": [ 
    { 
      "Name": "aa", 
      "Elements": [ 
        { 
         "category": "ss", 
            "Test1": 22, 
            "Test2": 33 ,
            "Test3":44,
            "Test4": 55 
        },
        { 
          "category": "ssee", 
          "Test12": 222, 
          "Test22": 3322 ,
          "Test32":445,
          "Test42": 553 
         }  
      ] 
    } 
  ] 
} 

];

我有这种方法,但它没有做好工作

var saveJson = function(arr) {
var nameValuePairs = [];
for (var i = 0, len = arr.length; i < len; i++) {
  var item = arr[i];
  if (item.Data) {
    var newvar = {
       category : item.Name
     }
     newvar[Object.keys(item.Data)] = Object.values(item.Data);
     item = newvar

  }

  if (item.Elements) {
    nameValuePairs = nameValuePairs.concat(saveJson(item.Elements));
  }
}
return arr;
};

我需要这种转换是动态的,因为我肯定会得到比发布的更大的json

对此感到困惑并提前感谢。

2 个答案:

答案 0 :(得分:1)

原始对象实际上是一团糟,但你只需要逐步完成它并提取你想要的值。这会更改Create a new Class and create 2 objects of your DateTime Class as given below: class Runner { DateTime currentDate = new CurrentDate(); currentDate.inputMonths(); currentDate.inputDays(); currentDate.inputHours(); currentDate.inputMinutes(); currentDate.inputSeconds(); //Now Create Another Object of DateTime Class: DateTime futureDate = new CurrentDate(); futureDate.inputMonths(); futureDate.inputDays(); futureDate.inputHours(); futureDate.inputMinutes(); futureDate.inputSeconds(); }//end of class Create ShowDate method in your DateTime class and call it with both the objects. 对象:

json

json.forEach(item => { item.Elements.forEach(Outer_El => { Outer_El.Elements = Outer_El.Elements.map(item =>{ let obj = {category: item.Name} Object.keys(item.Data).forEach(key => { obj[key] = item.Data[key][0] }) return obj }) }) }) 现在应该是这样的:

json

答案 1 :(得分:0)

您可以使用解构赋值从对象中获取特定属性值

{
  let {Name:categories, Data:{Test:[Test]}} = json[0].Elements[0].Elements[0];
  json[0].Elements[0].Elements[0] = {categories, Test};
}