我有 JSON,目前用于 kendo-ui 图表。我需要将数据用于网格,因此我需要将数组的嵌套数据数组分离到自己的对象中。 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"
}]
我需要最终得到两个单独的数组。
第一个数组
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');
});
关于javascript - 如何循环遍历对象数组和分隔嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30746153/