2020.10.14
逐层改变上一级的值
示例
// 如果 county里的所有 tag 都为true, 则上一级的当前city里的tag为true;如果city里的所有tag为true,则上一级testAll的当前tag为true;
// 如果 county里的某一个 tag 都为true, 则上一级的当前city里的status为true; 如果city里的 某一个tag为true,则上一级testAll的当前status为true;
输入:
let testAll = [
{
value: "A",
tag: false,
status: false,
pop: false,
city: [
{
value: "a-1",
tag: false,
status: false,
county: [
{ value: "aa-1", tag: true },
{ value: "aa-2", tag: false },
{ value: "aa-3", tag: true },
],
},
{
value: "a-2",
tag: false,
status: false,
county: [
{ value: "aa-1", tag: true },
{ value: "aa-2", tag: true },
{ value: "aa-3", tag: true },
],
}
],
}
]
输出:
{
value: 'A',
tag: false,
status: true,
pop: false,
city: [
{ value: 'a-1', tag: false, status: true, county: [Array] },
{ value: 'a-2', tag: true, status: true, county: [Array] }
]
}
实现
function changeStatus() {
testAll.forEach(item => {
// 获取第一层tag
let arr = item.city.reduce((result, val) => {
//第二层tag
val.tag = val.county.every(s => {
return s.tag == true
})
val.status = val.county.some(s => {
return s.tag == true
})
result.push({
tag:val.tag,
status:val.status
});
return result
}, [])
item.tag = arr.every(i => { return i.tag == true })
item.status = arr.some(i => { return i.status == true })
})
console.log(testAll[0])
}
changeStatus()
把所有组合穷举出来
示例
输入:
arrA = ['红色','白色'];
arrB = ['iphonex','iphonexs','iphone11];
输出:
arrC = [
['红色','iphonex'],
['红色','iphonexs'],
['红色','iphone11'],
['白色','iphonex'],
['白色','iphonexs'],
['白色','iphone11'],
]
实现
let arrA = ['红色','白色'];
let arrB = ['iphonex','iphonexs','iphone11];
let combine = function (...chunks) {
let res = [];
let helper = function (chunkIndex, prev) {
let chunk = chunks[chunkIndex]
let isLast = chunkIndex === chunks.length - 1
for (let val of chunk) {
let cur = prev.concat(val)
if (isLast) {
// 如果已经处理到数组的最后一项了 则把拼接的结果放入返回值中
res.push(cur)
} else {
helper(chunkIndex + 1, cur)
}
}
}
// 从属性数组下标为 0 开始处理
// 并且此时的 prev 是个空数组
helper(0, [])
return res
}
console.log(combine(arrA, arrA))