esafwan
esafwan

Reputation: 18029

Manipualte json with Js

I have a json as below. You can see a tree view of same here.

{

  "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"
      }
    ]
  }
}

As you you see the result is two level inside. Inside results, we again have collection1. The whole json is inside an object data. How can I move whole data in collection1 directly to results?

Some thing like.

var data.results = data.results.collections;

Can you do something like that?

Upvotes: 1

Views: 43

Answers (4)

Optimus
Optimus

Reputation: 116

If you are using Jquery , you can use var obj=$.extend({},data.results.collection1)

$.extend makes deep copy so obj will be independent object.

If you are using native JS,then use

var obj=Object.create(data.results.collection1) or var copy = Object.assign({}, data.results.collection1); // this is ES6 specific

Upvotes: 0

Silvio Zoidberg Sdord
Silvio Zoidberg Sdord

Reputation: 115

All you have to do is a new variable where you have the store the values that you want, in this case you want to store the values data.results.collection1 in a variable named results, so:

var results = data.results.collection1;

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68433

yes that should work, check this fiddle

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

Upvotes: 2

lakhan_Ideavate
lakhan_Ideavate

Reputation: 374

Create new object and try to assign

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

Upvotes: 0

Related Questions