多次循环问题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多次循环问题相关的知识,希望对你有一定的参考价值。
我有两个数组键和subGrps。使用这两个创建新数组,并将其映射键映射到subGrps数组。
var keys = ["Subgroup", "0-3", "3-10", "11-40"];
var subGrps = ["SP_20k", "SP_40k", "SP_60k"];
var arrayOfObjects = [];
subGrps.forEach(function(id)
keys.forEach(function(item)
if (item === "Subgroup")
arrayOfObjects.push(
[item]: id
);
else
arrayOfObjects.push(
[item]: ""
);
);
);
console.log(arrayOfObjects);
预期输出:
[
"Subgroup" : "SP_20k",
"0-3": "",
"3-10": "",
"11-40": ""
,
"Subgroup" : "SP_40k",
"0-3": "",
"3-10": "",
"11-40": ""
,
"Subgroup" : "SP_60k",
"0-3": "",
"3-10": "",
"11-40": ""
]
forEach
是个好选择吗?用于将keys array
和subGrps array
的对象分组以获得该输出。我缺少获得预期输出的什么?有人可以帮助我吗?
您可以使用Array.map
遍历Array.map
数组,使用subGrps
键设置为Subgroup
中的值来创建对象,并使用subGrps
为[[ C0]数组:
Object.assign
尝试一下,
keys
如果您要特别对待var keys = ["Subgroup", "0-3", "3-10", "11-40"];
var subGrps = ["SP_20k", "SP_40k", "SP_60k"];
var arrayOfObjects = subGrps.map(v => Object.assign(
"Subgroup": v
,
...keys.slice(1).map(k => (
[k]: ""
))
));
console.log(arrayOfObjects);
,为什么不将var keys = ["Subgroup", "0-3", "3-10", "11-40"];
var subGrps = ["SP_20k", "SP_40k", "SP_60k"];
var arrayOfObjects = subGrps.map(v => Object.assign(,
...keys.map(k => (
[k]: k == 'Subgroup' ? v : ""
))
));
console.log(arrayOfObjects);
与其他键混在一起,但是您可以使用:
const arr = [];
subGrps.forEach(subGrp =>
const obj =
keys.forEach(key => obj[key] = (key === 'Subgroup') ? subGrp : '' );
arr.push(obj);
)
console.log(arr)
您需要执行此操作:
"Subgroup"
我对您的代码做了如下修改:
const [sgKey, ...keys] = ["Subgroup", "0-3", "3-10", "11-40"];
const subGrps = ["SP_20k", "SP_40k", "SP_60k"];
const result = subGrps.map(sg =>
const obj =
[sgKey]: sg
for (const k of keys)
obj[k] = ''
return obj
);
console.log(result)
以上是关于多次循环问题的主要内容,如果未能解决你的问题,请参考以下文章