验证中...
Javascript对象数组根据某个相同字段做分组
Raw Copy
<script>
var arr = [
{ "id": "1001", "pId": "1001", "value": "111" },
{ "id": "1001", "pId": "1001", "value": "11111" },
{ "id": "1002", "pId": "1002", "value": "25462" },
{ "id": "1002", "pId": "1002", "value": "23131" },
{ "id": "1002", "pId": "1002", "value": "2315432" },
{ "id": "1003", "pId": "1003", "value": "333333" }
];
console.log(arr)
var map = {},
dest = [];
for (var i = 0; i < arr.length; i++) {
var ai = arr[i];
if (!map[ai.pId]) {
// console.log('ai', arr[i])
dest.push({
id: ai.id,
pId: ai.pId,
children: [ai]
})
map[ai.pId] = ai;
// console.log('ai1', ai)
} else {
for (var j = 0; j < dest.length; j++) {
var dj = dest[j];
if (dj.id == ai.id) {
dj.children.push(ai);
break;
}
}
}
}
console.log('ai', dest)
// console.log(dest);
</script>
ceshi.html
Raw Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>封装ajax</title>
<!-- <script src="js/fenzhuang.js"></script>
<script src="js/fengzhuang-index.js"></script> -->
</head>
<body>
<script>
var arr = [
{ "id": "1001", "pId": "1001", "value": "111" },
{ "id": "1001", "pId": "1001", "value": "11111" },
{ "id": "1002", "pId": "1002", "value": "25462" },
{ "id": "1002", "pId": "1002", "value": "23131" },
{ "id": "1002", "pId": "1002", "value": "2315432" },
{ "id": "1003", "pId": "1003", "value": "333333" }
];
console.log(arr)
var map = {},
dest = [];
for (var i = 0; i < arr.length; i++) {
var ai = arr[i];
if (!map[ai.pId]) {
// console.log('ai', arr[i])
dest.push({
id: ai.id,
pId: ai.pId,
children: [ai]
})
map[ai.pId] = ai;
// console.log('ai1', ai)
} else {
for (var j = 0; j < dest.length; j++) {
var dj = dest[j];
if (dj.id == ai.id) {
dj.children.push(ai);
break;
}
}
}
}
console.log('ai', dest)
// console.log(dest);
</script>
</body>
</html>

Comment list( 0 )

You need to Sign in for post a comment

Help Search