[英]how to loop through array of objects and separate nested array of arrays
我有目前用於kendo-ui圖表的JSON。 我需要將數據用於網格,因此需要將數組的嵌套數據數組分離為自己的對象。 Javascript或linq.js可以正常工作。 這是我開始使用的JSON。
customSeries = [{
"name": "Chantal Hamlet - Green Castle Homes",
"subId": "10223",
"bldId": "13551",
"data": [
[179900, 1386],
[214900, 1440],
[194500, 1496],
[217900, 1504],
[189900, 1542],
[184900, 1546],
[192500, 1570]
],
}, {
"name": "Ella Sea Condos - Sahnow Construction",
"subId": "9761",
"bldId": "27380",
"data": [
[199900, 1500]
]
}, {
"style": "smooth",
"color": "blue",
"data": [
[20000, 200],
[40000, 400],
[40000, 400]
],
"name": "Subject Property"
}]
我需要結束於2個單獨的數組。
第一陣列
Array1 = [{
"name": "Chantal Hamlet - Green Castle Homes",
"subId": "10223",
"bldId": "13551"
}, {
"name": "Ella Sea Condos - Sahnow Construction",
"subId": "9761",
"bldId": "27380"
}, {
"style": "smooth",
"color": "blue",
"name": "Subject Property"
}]
第二陣列
Array2 = [
{
"data": [
[179900, 1386],
[214900, 1440],
[194500, 1496],
[217900, 1504],
[189900, 1542],
[184900, 1546],
[192500, 1570]
]
}, {
"data": [
[199900, 1500]
]
}, {
"data": [
[20000, 200],
[40000, 400],
[40000, 400]
]
}
]
您可以使用Array.prototype.map
方法。
var Array1 = customSeries.map(function(el) {
return {
name: el.name,
subId: el.subId,
bldId: el.bldId
};
});
var Array2 = customSeries.map(function(el) {
return {
data: el.data
};
});
更新:
當customSeries
的元素沒有data
以外的固定鍵時,以上代碼不起作用。
如果使用lodash
,則可以執行以下操作:
var Array1 = customSeries.map(function(el) {
return _.omit(el, 'data');
});
var Array2 = customSeries.map(function(el) {
return _.pick(el, 'data');
});
根據數組的長度,您可能希望一次完成此操作。 在這里使用linq.js並沒有多大幫助,只會增加開銷,而沒有真正的好處。
如果您不希望刪除原始數據,則可以通過遍歷每個項目來同時處理它們,並在從項目中刪除數據的同時將data
數組的副本添加到第二個數組中。
var array1 = data,
array2 = [];
array1.forEach(function (item) {
array2.push({
data: item.data
});
delete item.data;
});
如果您希望保留原始數據,則必須在處理它們時克隆每個項目。
var array1 = [],
array2 = [];
data.forEach(function (item) {
var noData = yourCloneMethod(item); // replace call with preferred clone method
delete noData.data;
array1.push(noData);
array2.push({
data: item.data
});
});
您可能想研究使用lodash ,它具有許多出色的函數,可用於處理數組和執行MapReduce函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.