【问题标题】:Programmatically Adding Properties to Objects in Javascript以编程方式向 Javascript 中的对象添加属性
【发布时间】:2018-12-06 22:33:06
【问题描述】:

我正在尝试以编程方式向对象添加属性。不过这个案例有点不同,我不知道如何处理这个问题。

通常,要将属性应用于对象,我会在此上下文中应用它:

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

感谢大家的宝贵时间!

【问题讨论】:

  • creates b1-b17 usually 真的吗?它应该创建类似b0-b17
  • 如果您为tableData 提供一些输入数据并显示您想要的输出,我会更容易理解您的要求。
  • 所以您希望tableData 的每个成员都转换为b0..b17 类型值的数组?完全不清楚你想达到什么目的
  • @CertainPerformance 它确实创建了 b0-b17,我的错。我没有校对那部分。
  • 为什么你的“上下文”代码不是const values = {}; for(g = 0; g&lt;len; g++) { values["b"+g] = []; }

标签: javascript function dynamic properties


【解决方案1】:

您可以使用reduce()['data1', 'data2', 'data3', 'data4'] 之类的数组转换为具有column1 之类的动态键的对象。例如:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    • 2017-12-05
    • 1970-01-01
    • 2016-12-30
    • 2018-04-25
    • 2011-11-09
    相关资源
    最近更新 更多