2015-12-30 70 views
1

我有一個json如下。您可以看到same here的樹狀圖。Manipual json與Js

{ 

    "results": { 
    "collection1": [ 
     { 
     "property1": { 
      "href": "http://www.somesite.com/neatobambino/2015/12/29/Little-Girl-Uses-Dogs-Tail-as-a-Paintbrush/", 
      "text": "Little Girl Uses Dog's Tail as a Paintbrush" 
     }, 
     "property5": { 
      "alt": "", 
      "src": "", 
      "text": "" 
     }, 
     "index": 1, 
     "url": "http://www.somesite.com/" 
     },     

     { 
     "property1": { 
      "href": "http://www.somesite.com/2015/09/11/20-Alternative-Housing-Solutions-for-the-Homeless/", 
      "text": "20 Alternative Housing Solutions for the Homeless" 
     }, 
     "property5": [ 
      { 
      "alt": "", 
      "src": "http://www.somesite.com/page/data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=", 
      "text": "" 
      }, 
      { 
      "alt": "", 
      "src": "http://www.somesite.com/page/data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=", 
      "text": "" 
      } 
     ], 
     "index": 2500, 
     "url": "http://www.somesite.com/page/84" 
     } 
    ] 
    } 
} 

正如你所看到的結果是兩個層面裏面。在results裏面,我們再次有collection1。整個json在一個對象data內。如何將collection1中的整個數據直接移動到results

有些事情。

var data.results = data.results.collections; 

你可以這樣做嗎?

回答

2

是的,這應該工作,檢查該fiddle

obj.results = obj.results.collection1; 
console.log(obj); 
+0

我會試試看。謝謝.. – esafwan

0

創建新的對象,並嘗試分配

var newData = { 
"results": data.results.collections; 
} 
+0

我會試一試。非常感謝。 – esafwan

0

所有你需要做的就是,你有實體店的值的新變量你想在這種情況下,你想要將值data.results.collection1存儲在名爲results的變量中,所以:

var results = data.results.collection1; 
+0

我會試試看。謝謝。 – esafwan

0

如果你使用jQuery,您可以使用 VAR OBJ = $。延長({},data.results.collection1)

$ .extend使深層副本,以便OBJ將是獨立的對象。

如果使用天然JS,然後使用

VAR OBJ =的Object.create(data.results.collection1) 或 變種複製= Object.assign({},data.results.collection1); //這是ES6特定的

+0

我會試試看。謝謝。 – esafwan