重新排列javascript对象结构

时间:2017-04-18 19:46:12

标签: javascript json

我正在查看具有以下结构的对象:

[
  [
    {
      "attr1":"1",
      "attr2":"2",
      "attr3":"3"
    }
  ],
  [
    {
      "attr1":"1",
      "attr2":"2",
      "attr3":"3"
    }
  ],
  [
    {
      "attr1":"1",
      "attr2":"2",
      "attr3":"3"
    }
  ]
]

只关注它的结构,我需要对这个对象进行重新排列,以便最终得到以下结构:

[
  {
    "attr1":"1",
    "attr2":"2",
    "attr3":"3"
  },
  {
    "attr1":"1",
    "attr2":"2",
    "attr3":"3"
  },
  {
    "attr1":"1",
    "attr2":"2",
    "attr3":"3"
  }
]

如何在纯Javascript或核心jQ库中完成?

3 个答案:

答案 0 :(得分:2)

因此,您只需要删除二级数组。使用 Array.map() 轻松完成。



var old = [
  [
    {
      "attr1":"1",
      "attr2":"2",
      "attr3":"3"
    }
  ],
  [
    {
      "attr1":"1",
      "attr2":"2",
      "attr3":"3"
    }
  ],
  [
    {
      "attr1":"1",
      "attr2":"2",
      "attr3":"3"
    }
  ]
];

// Map loops through an array and returns a new array filled with whatever the 
// supplied callback function returns. 
var newArry = old.map(function(value){
  // Get the first object stored in the second-level array, but not the array itself
  return value[0];  
});

console.log(newArry);




答案 1 :(得分:0)

Array#reduce可能会有所帮助。

var arr = [[{"attr1":"1","attr2":"2","attr3":"3"}],[{"attr1":"1","attr2":"2","attr3":"3"}],[{"attr1":"1","attr2":"2","attr3":"3"}]], 
    res = arr.reduce((a,b) => a.concat(b));

    console.log(res);

答案 2 :(得分:0)

您可以将Array#concatspread syntax ...一起使用。



var data = [[{ attr1: "1", attr2: "2", attr3: "3" }], [{ attr1: "1", attr2: "2", attr3: "3" }], [{ attr1: "1", attr2: "2", attr3: "3" }]],
    flat = [].concat(...data);

console.log(flat);

.as-console-wrapper { max-height: 100% !important; top: 0; }




ES5



var data = [[{ attr1: "1", attr2: "2", attr3: "3" }], [{ attr1: "1", attr2: "2", attr3: "3" }], [{ attr1: "1", attr2: "2", attr3: "3" }]],
    flat = [].concat.apply([], data);

console.log(flat);

.as-console-wrapper { max-height: 100% !important; top: 0; }