在您投反对票或将其标记为重复之前,请完整阅读问题。
我正在寻找一种在对象中合并多个数组道具的有效方法。
对象可以在那里具有多个数组属性:
{
"col0Codes": [
"ABC",
"XYZ",
"UYA",
"ZZA",
"AAW",
"MYP"
],
"col1Codes": [
"CNA",
"ZYA",
"OIA",
"POQ",
"LMO",
"OPI"
],
"col2Codes": [
"CNA",
"ZYA",
"OIA",
"POQ",
"LMO",
"OPI"
],
"col3Codes": [
"..."
],
"col4Codes": [
"..."
],
...
}
结果:所有代码都在一个数组中
["ABC","XYZ","UYA","ZZA","AAW","MYP","CNA","ZYA","OIA","POQ","LMO","OPI",....]
我尝试使用concat
,但这每次都会创建一个新数组并覆盖前一个数组,我觉得这样做并不快且内存效率很高。
let colCodes = []
for (let i in data) {
colCodes = colCodes .concat(i)
}
console.log(activityCodes)
我尝试使用push
,但是由于某种原因,它不会将所有条目合并到一个数组中,而是在对象中创建一个包含多个道具的数组,如下所示
let colCodes = []
for (let i in data) {
colCodes.push(i)
}
console.log(colCodes)
[Array(6), Array(5), ....]
无论如何,我可以使用reduce
来做到这一点吗?
答案 0 :(得分:4)
您可以获取Object.values()
,然后将spreading合并到Array.concat()
中:
const data = {"col0Codes":["ABC","XYZ","UYA","ZZA","AAW","MYP"],"col1Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"],"col2Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"]};
const result = [].concat(...Object.values(data));
console.log(result);
答案 1 :(得分:2)
一种方法是使用Array.prototype.flat
,然后在对象的值上调用它:
const input={"col0Codes":["ABC","XYZ","UYA","ZZA","AAW","MYP"],"col1Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"],"col2Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"]};
console.log(
Object.values(input).flat()
);
答案 2 :(得分:1)
您也可以通过ES6传播简单地Array.reduce
Object.values
:
const input={"col0Codes":["ABC","XYZ","UYA","ZZA","AAW","MYP"],"col1Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"],"col2Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"]};
console.log(Object.values(input).reduce((r,c) => [...r, ...c]))
答案 3 :(得分:0)
您可以尝试
let obj = {"col0Codes": ["ABC","XYZ","UYA","ZZA","AAW","MYP"],
"col1Codes": ["CNA","ZYA","OIA","POQ","LMO","OPI"],
"col2Codes": ["CNA","ZYA","OIA","POQ","LMO","OPI"],
"col3Codes": ["..."],
"col4Codes": ["..."]
}
let op = [];
for(let key in obj){
op.push(...obj[key])
}
console.log(op)