我有對象的數組:轉換對象數組不同的對象
[{ bags:10, pouch:small, weight:100, quantity:1 },
{ bags:101, pouch:large, weight:1001, quantity:11 }]
如何可以分離該陣列分成多個對象如下所示?
small = { bags:10,weight:100,quantity:1 }
large = { bags:101,weight:1001,quantity:11 }
我有對象的數組:轉換對象數組不同的對象
[{ bags:10, pouch:small, weight:100, quantity:1 },
{ bags:101, pouch:large, weight:1001, quantity:11 }]
如何可以分離該陣列分成多個對象如下所示?
small = { bags:10,weight:100,quantity:1 }
large = { bags:101,weight:1001,quantity:11 }
因此,步驟是:
找到您想要的條目,
的小袋
複製創建一個對象你想要的屬性
所以:
var array = [{ bags:10,pouch:"small",weight:100,quantity:1},{bags:101,pouch:"large",weight:1001,quantity:11}];
var small = get(array, "small");
var large = get(array, "large");
snippet.log("small = " + JSON.stringify(small));
snippet.log("large = " + JSON.stringify(large));
function get(array, pouch) {
// Find the entry (on newer browsers you could use Array#find, and it
// can be shimmed; I used Array#some here)
var found;
array.some(function(entry) {
if (entry.pouch == pouch) {
found = entry;
return true;
}
});
if (found) {
// Found it, create an object with the properties we want
return {
bags: found.bags,
weight: found.weight,
quantity: found.quantity
};
}
return null;
}
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
感謝您的幫助! @ T.J.Crowder如果對象內的內容是未知的,我怎樣才能遍歷對象內的所有值,然後將其分開? – HarshMakadia
@HarshMakadia:請參閱Nina關於用每個袋子的屬性創建對象的回答。 –
這樣做,但我不推薦它!
var data = [{ bags: 10, pouch: 'small', weight: 100, quantity: 1 }, { bags: 101, pouch: 'large', weight: 1001, quantity: 11 }],
object = data.forEach(function (a) {
window[a.pouch] = { bags: a.bags, weight: a.weight, quantity: a.quantity };
});
document.write('<pre>' + JSON.stringify(small, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(large, 0, 4) + '</pre>');
更好的解決方案與對象
你可以先建立一個與pouch
值屬性的對象,後來分配他們想要的變量。
var data = [{ bags: 10, pouch: 'small', weight: 100, quantity: 1 }, { bags: 101, pouch: 'large', weight: 1001, quantity: 11 }],
object = data.reduce(function (r, a) {
r[a.pouch] = { bags: a.bags, weight: a.weight, quantity: a.quantity };
return r;
}, {});
document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');
var small = object.small,
large = object.large;
document.write('<pre>' + JSON.stringify(small, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(large, 0, 4) + '</pre>');
@NinaScholz如果對象內的內容是動態生成的,我該如何獲取它們呢? – HarshMakadia
@HarshMakadia,我建議使用一個對象,並將所有值保存在一起。 –
@HarshMakadia:在這種情況下,就像Nina說的那樣,一個對象(或者現代引擎上的'Map',如果合適的話)來組織它們是正確的方法。 –
我認爲[Array.reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce)是去這裏的路。 – A1rPun
@ A1rPun:不,如果生成多個輸出則不行。 –
你卡在哪裏?您只需找到「小」的條目,創建一個對象,將相關的道具複製到其中,併爲「大」做同樣的事情。 –