Manipualte json with Js

Manipualte json with Js

本文关键字:Js with json Manipualte      更新时间:2023-09-26

我有一个json,如下所示。你们可以在这里看到相同的树视图。

{
  "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;

你能做这样的事吗?

是的,应该工作,检查这个小提琴

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

创建新对象并尝试分配

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

您所要做的就是创建一个新变量,在其中存储您想要的值,在这种情况下,您想要将值data.results.collection1存储在一个名为results的变量中,因此:

var results = data.results.collection1;

如果使用Jquery,可以使用var obj=$.extend({},data.results.collection1)

$.extend进行深度复制,因此obj将是独立的对象。

如果您使用的是原生JS,那么请使用

var obj=Object.create(data.results.collection1)或var copy=Object.assign({},data.results.collection1);//这是ES6特定的