2016-11-30 49 views

回答

1

我想通過遍歷每個對象的鑰匙,並添加鍵接近這個散列到您的值對象。

var vals = {} 
var src = [{ Color="Blues", Shape="Octagon", Thickness="High (Over 1 Inch)"}, { Color="Burgundys", Shape="Oval", Thickness="3⁄8 (approx.)"}] 

src.forEach(function(obj){ 

    for(var key in obj){ 
     if(vals[ key ] === undefined) 
      vals[ key ] = [] 

     vals[ key ].push(obj[ key ]) 
    } 

}) 
+0

Object {Color = [1],Shape = [1],Thickness = [1],more ...}它給這個對象帶有球杆值 – sunnyn

+0

我剛剛從你的代碼中複製了源數組。顯然這會引發運行時錯誤,但是太懶惰,無法正確格式化您的src數組。現在修復它。 – jusopi

0

這應該做你想要什麼:

a = [{foo: 1, bar: 2}, {foo: 3, bar: 4}] 
a.reduce((acc, val) => { 
    for (var key in val) { 
    if (!val.hasOwnProperty(key)) continue; 
    if (!acc.hasOwnProperty(key)) acc[key] = [] 
    acc[key].push(val[key]) 
    } 
    return acc 
}, {}) 
+0

很好的使用'Array.prototype.reduce' :) – jusopi

0

看起來你必須做一個循環,讓你在找什麼。

var colors = []; 
var shapes = []; for(var i = 0;i<objArray.length;i++) 
{ 
    colors[i] = objArray[i].color 
    shapes[i] = objArray[i].shape 
} 
answer = {}; 
answer.colors = colors; 
answer.shapes = shapes; 
0

您將會遍歷對象並存儲唯一的結果。以下是編寫這種近似方法:

var colors = [], shapes = []; 

for (var i = 0; i < object.length; i++) { 
    var color = object[i].Color, shape = object[i].Shape; 
    if (colors.indexOf(color) === -1) { colors.push(color); } 
    if (shapes.indexOf(shape) === -1) { shapes.push(shape); } 
} 

result = {"Color": colors, "Shape": shapes}; 
0
var arr = [{ 
    color: "Blues", 
    Shape: "Octagon" 
}, 
{ 
color: "Burgundys", 
Shape="Oval" 
}] 

var targetObject = {}; 

for(var iloop=0; iloop< arr.length; iloop++){ 
    //get the keys in your object 
    var objectKeys = Object.keys(arr[iloop]); 

    //loop over the keys of the object 
    for(var jloop=0; jloop<objectKeys.length; jloop++){ 
    //if the key is present in your target object push in the array 
    if(targetObject[ objectKeys[jloop] ]){ 
     targetObject[objectKeys[jloop]].push(arr[iloop][objectKeys[jloop]]); 
    }else{ 
     // else create a array and push inside the value 
     targetObject[objectKeys[jloop]] = [] 
     targetObject[objectKeys[jloop]].push(arr[iloop][objectKeys[jloop]] ); 
    } 
    } 
} 
相關問題