以编程方式向Javascript对象添加属性

时间:2018-06-27 23:34:22

标签: javascript function dynamic properties

我正在尝试以编程方式将属性添加到对象。不过,这种情况有些不同,我不确定如何解决此问题。

通常,要将属性应用于对象,我会在这种情况下应用它:

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
  }
})

谢谢你们的时间!

1 个答案:

答案 0 :(得分:1)

您可以使用['data1', 'data2', 'data3', 'data4']将像column1这样的数组变成带有像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)

相关问题