0
我有一個對象,作爲一個ID作爲密鑰和對象值的陣列,我需要生成從該操縱對象值,併產生一個新的對象
的目標的矩陣
var bears = {
"1" :
[
{ 'total_bears': 2, 'bear_id': 1, 'location': 'CA' },
{ 'bear_age': 100, 'bear_id': 1, 'location': 'CA' },
{ 'total_bears': 1, 'bear_id': 1, 'location': 'NM' },
{ 'bear_age': 10, 'bear_id': 1, 'location': 'NM' }
],
"2" :
[
{ 'total_bears': 1, 'bear_id': 2, 'location': 'CA' },
{ 'bear_age': 50, 'bear_id': 2, 'location': 'CA' }
]
};
結果
{ 'bear_id' : 1, 'locationCAtotal_bears' : 2, 'locationCAbear_age': 100, 'locationNMtotal_bears': 1, 'locationNMbear_age': 100}
{ 'bear_id' : 2, 'locationCAtotal_bears' : 1, 'locationCAbear_age': 50}
我有什麼
for (var key in bears) {
var arr = bears[key];
var obj = {};
var new_arr = arr.map(function(item) {
if (item.location == 'CA') {
obj.bear_id = item.bear_id;
obj.locationCAtotal_bears = item.total_bears;
obj.locationCAbear_age = item.bear_age;
}
else if (item.location == 'NM') {
obj.bear_id = item.bear_id;
obj.locationNMtotal_bears = item.total_bears;
obj.locationNMbear_age = item.bear_age;
}
return obj
});
}
這是我嘗試過的許多代碼之一。我已經嘗試了不同的東西就可以了,但仍然沒有運氣
請向我們提供您迄今爲止所做的工作。然後,我們將能夠指出你的錯誤 –
@NafiulIslam我已經添加了我寫的代碼 – akinjide