2017-04-18 88 views
-1

我在看與以下結構的對象:重新排列JavaScript對象結構

[ 
    [ 
    { 
     "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庫中完成的?

+0

所以,你只是想借此每個內部數組的第一個元素?你可以用'myArray.map(x => x [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);

+0

您預期只有一個數組中的項目,它看起來不是很通用。 –

+0

@NinaScholz真的,但是當他說他正在處理的結構是什麼時,OP是特定的。 –

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);

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; }

+0

@ScottMarcus,第二個應該適用於較老的JavaScript實現。 –