5 回答
TA贡献1847条经验 获得超7个赞
您可以使用 Array.map
循环访问数组,创建一个将键设置为 from 值的对象,并使用 Object.assign
为数组中的其他条目添加空值:subGrps
Subgroup
subGrps
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);
TA贡献1851条经验 获得超3个赞
您可以先创建对象,然后在循环中添加键。
var keys = ["Subgroup", "0-3", "3-10", "11-40"];
var subGrps = ["SP_20k", "SP_40k", "SP_60k"];
// creates the object with keys once
// you can also use foreach to create this keysObj too.
var keysObj = keys.reduce((resObj, acc) => {
resObj[acc] = ''
return resObj
}, {})
// uses keysObj to generate array of objects
var arrayOfObjects = subGrps.map(subGrp => ({...keysObj, Subgroup: subGrp}))
console.log(arrayOfObjects)
TA贡献1875条经验 获得超3个赞
如果你想特别对待它,我不知道为什么与其他键混在一起,但在这里你去:"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)
TA贡献1820条经验 获得超9个赞
您需要执行以下操作:
var keys = ["Subgroup", "0-3", "3-10", "11-40"];
var subGrps = ["SP_20k", "SP_40k", "SP_60k"];
var arrayOfObjects = [];
subGrps.forEach(function(id) {
var obj = {}
keys.forEach(function(item) {
if (item === "Subgroup") {
obj[item]= id
arrayOfObjects.push(obj);
} else {
obj[item] = ""
arrayOfObjects.push(obj);
}
});
});
console.log(arrayOfObjects);
TA贡献1847条经验 获得超11个赞
试试这个,
const arr = [];
subGrps.forEach(subGrp => {
const obj = {}
keys.forEach(key => obj[key] = (key === 'Subgroup') ? subGrp : '' );
arr.push(obj);
})
console.log(arr)
添加回答
举报