我正在尝试以编程方式向对象添加属性。不过,这种情况有点不同,我不确定如何解决这个问题。
通常,要将属性应用于对象,我会在以下上下文中应用它:
var a = []
var len = result[0].length
for(m=0; m < len; m++){
a[m] = "b" + m // creates b1-b17 usually, but if the results are shorter it will create them equal to the length of the results
}
const values = {}
for(g=0; g<len; g++){
values[a[g]] = [];
}
这通常会向“b1”到“b17”的每个属性添加一个空数组,但它是动态的,以防结果较短。
现在我想对这段代码做同样的事情,但只在“返回”部分内。无论如何,我可以调用它并像我以前所做的那样以编程方式输入这些变量吗?
const rowData = tableData.map(result => {
for(var h in a){
values[a[h]].push(result[h]);
}
return {
//I want to put properties in here programmatically and dynamically like I did previously
}
})
谢谢你们的时间!
您可以将类似数组['data1', 'data2', 'data3', 'data4']
的对象转换为具有动态键的对象,例如column1
using reduce()
。例如:
let arr = ['data1', 'data2', 'data3', 'data4']
let obj = arr.reduce((a, c, i) => (a['column' + (i + 1)] = c, a), {} )
console.log(obj)
有了这个,给定一个这样的数组数组,你可以将它与它结合map()
以获得最终结果:
let tableData = [['data1', 'data2', 'data3', 'data4'], ['data11', 'data22', 'data33', 'data44']]
// for each array in tableData make an object with reduce and add it to the returned array
let result = tableData.map(arr => arr.reduce((a, c, i) => (a['column' + (i + 1)] = c, a), {} ))
console.log(result)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句