文章目录
- 1 使用reduce求和
- 2 将js对象转化为树形结构
1 使用reduce求和
- arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],求和
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function add(arr) {
let sum = arr.reduce((total, item) => total + item, 0);
return sum;
}
console.log(add(arr));
- arr = [1, 2, 3, [[4, 5], 6], 7, 8, 9],求和
arr = [1, 2, 3, [[4, 5], 6], 7, 8, 9];
function add(arr) {
let sum = arr.flat(Infinity).reduce((total, item) => total + item, 0);
return sum;
}
console.log(add(arr));
- arr = [{ a: 1, b: 3 }, { a: 2, b: 3, c: 4 }, { a: 3 }],求和
arr = [{ a: 1, b: 3 }, { a: 2, b: 3, c: 4 }, { a: 3 }];
function add(arr) {
let sum = arr.reduce((total, item) => total + item['a'], 0);
return sum;
}
console.log(add(arr));
2 将js对象转化为树形结构
source = [{
id: 1,
pid: 0,
name: 'body'
}, {
id: 2,
pid: 1,
name: 'title'
}, {
id: 3,
pid: 2,
name: 'div'
}];
tree = [{
id: 1,
pid: 0,
name: 'body',
children: [{
id: 2,
pid: 1,
name: 'title',
children: [{
id: 3,
pid: 1,
name: 'div'
}]
}]
}];
function jsonToTree(data) {
let result = [];
if (!Array.isArray(data)) return result;
let map = {};
data.forEach(item => {
map[item.id] = item;
});
data.forEach(item => {
let parent = map[item.pid];
if (parent) {
(parent.children || (parent.children = [])).push(item);
} else {
result.push(item);
}
});
return result;
}