2016-04-27 90 views
1

我正在嘗試重建一個數組,因此我需要使用最佳實踐進行建議。 我有一個數組對象如下:修改數組對象

MainObject: 
0:"Namebar" 
    1: Object 
    Name: "Title1" 
    Url: "Url1" 
    2: Object 
    Name: "Title2" 
    Url: "Url2" 
    3: Object 
    Name: "Title3" 
    Url: "Url1" 

在上述自「URL」是相同的,我想組它相同的對象和我期待以下列格式的輸出:

0: "Url1" 
    1: Object 
    Name : "Title1" 
    Url: "Namebar" 
    2: Object 
    Name : "Title3" 
    Url: "Namebar" 

1: "Url2" 
    1: Object 
    Name : "Title2" 
    Url: "Namebar" 

我想要有兩個數組,並通過MainObject循環來交換項目,我知道這不僅是一個費時的過程,而且還有很高的時間複雜度。 例如喜歡:

var extract1 = MainObject[0]; 
var extract2 = using for loop to extract and swap ...... 

我沒有得到實現這一目標的任何其他方式。任何方法在JavaScript/jQuery中的這個?

+0

什麼是在'MainObject'的屬性名'Namebar'?在MainObject中的數組的屬性名是什麼? –

+0

@AlexArt .:沒有Namebar的屬性名,只是MainObject [0]給出的輸出爲「Namebar」,而MainObject [1]和2是具有上述結構的數組 – user1400915

+0

你如何獲得嵌套數組? –

回答

3

這應該做的工作:

var extract1 = MainObject[0]; 
var newArray = {}; 
var newArrProp; 
var extract1Props = Object.keys(extract1); 
for(i = 0; i< extract1Props.length; i++) 
{ 
    newArrProp = extract1Props[i]; 
    var nestedObjects = extract1[newArrProp]; 
    for(j = 0; j < nestedObjects.length; j++) 
    { 
     if(!newArray[nestedObjects[j].Url]) 
     { 
      newArray[nestedObjects[j].Url] = [];    
     } 
     newArray[nestedObjects[j].Url].push({Name:nestedObjects[j].Name,Url:newArrProp}); 
    } 
} 

Working fiddle

2

你可以使用一些循環。

var MainObject = [{ "Namebar": [{ Name: "Title1", Url: "Url1" }, { Name: "Title2", Url: "Url2" }, { Name: "Title3", Url: "Url1" }] }], 
 
    object2 = []; 
 

 
MainObject.forEach(function (a) { 
 
    Object.keys(a).forEach(function (k) { 
 
     a[k].forEach(function (b) { 
 
      var temp = {}; 
 
      if (!this[b.Url]) { 
 
       temp[b.Url] = []; 
 
       this[b.Url] = temp[b.Url]; 
 
       object2.push(temp); 
 
      } 
 
      this[b.Url].push({ name: b.Name, Url: k }); 
 
     }, this); 
 
    }, this); 
 
}, Object.create(null)); 
 

 
document.write('<pre>object2 ' + JSON.stringify(object2, 0, 4) + '</pre>'); 
 
document.write('<pre>MainObject ' + JSON.stringify(MainObject, 0, 4) + '</pre>');