[Object { Color="Blues", Shape="Octagon", Thickness="High (Over 1 Inch)", more...}, Object { Color="Burgundys", Shape="Oval", Thickness="3⁄8" (approx.)", more...}]
我想輸出:
[{"Color":["Blues","Burgundys "],"Shape":['Octagon',"Oval"]}]
同爲他人重視
[Object { Color="Blues", Shape="Octagon", Thickness="High (Over 1 Inch)", more...}, Object { Color="Burgundys", Shape="Oval", Thickness="3⁄8" (approx.)", more...}]
我想輸出:
[{"Color":["Blues","Burgundys "],"Shape":['Octagon',"Oval"]}]
同爲他人重視
我想通過遍歷每個對象的鑰匙,並添加鍵接近這個散列到您的值對象。
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 ])
}
})
這應該做你想要什麼:
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
}, {})
很好的使用'Array.prototype.reduce' :) – jusopi
看起來你必須做一個循環,讓你在找什麼。
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;
您將會遍歷對象並存儲唯一的結果。以下是編寫這種近似方法:
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};
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]] );
}
}
}
,是語言? –
Javascript語言 – sunnyn