删除嵌套的json元素并显示为单独的键值对

时间:2013-03-28 18:40:19

标签: javascript json

我想删除嵌套的json对象并将其单独显示为键值对。这是我的json对象

[
  {
    "fileId": 123,
    "fileName": "test file.zip",
    "createdOnDate": "2013-03-22T17:02:00",    
    "valueList": {
      "text_box": "Testing textbox",
      "text_area": "Lorem ipsum dolor sit"
    }
  }
]

如何对其进行格式化以使对象看起来像

[
  {
    "fileId": 123,
    "fileName": "test file.zip",
    "createdOnDate": "2013-03-22T17:02:00",    
    "text_box": "Testing textbox",
      "text_area": "Lorem ipsum dolor sit"

  }
]

使用jquery?

2 个答案:

答案 0 :(得分:0)

试试这个:

theArray.forEach(function(item) {
    item.text_box = item.valueList.text_box;
    item.text_area = item.valueList.text_area;
    delete item.valueList;
});

答案 1 :(得分:0)

这是一个简单但并非包罗万象的解决方案。

function unseat(obj, prop) {
    for(var k in obj[prop])
        obj[k] = obj[prop][k];
    delete obj[prop];
    return obj;
}
var testObj =   {
    "fileId": 123,
    "fileName": "test file.zip",
    "createdOnDate": "2013-03-22T17:02:00",    
    "valueList": {
      "text_box": "Testing textbox",
      "text_area": "Lorem ipsum dolor sit"
    }
  };
testObj = unseat(testObj, "valueList");
for(var k in testObj) 
    console.log(k + " " + testObj[k]);