如何从对象内部获取属性名称以创建新的属性名称?

时间:2019-03-22 19:33:29

标签: javascript object properties

我知道有关该主题的其他文章,但似乎并没有解决我的问题:link

我希望能够动态获取对象中特定属性的名称,以便可以使用它在另一个对象中创建新的属性名称。例如,我将从startMin获得属性名称foo(如下面的代码所示),然后在其末尾添加文本(例如startMin + Suffix)以创建新的属性名称。我怎样才能做到这一点?

相关说明:我已经想出了如何使用foo[Object.keys(foo)[0]]获取属性值。尽管这可行,但我不确定为什么在这种情况下Object.keys获得属性值,因为我发现的示例建议Object.keys应该获得属性名称而不是属性值。我想知道为什么吗?

我包括了pusdo代码foo[Object.returnObjectName(foo)[0]] + 'Cal',我想在其中动态创建名称。当然不行。

var foo = {
  startMin: 1000
};

var fooResults = {
  // the property name here is psudo code 
  foo[Object.returnObjectName(foo)[0]] + 'Cal': foo[Object.keys(foo)[0]]
}

console.log('startMinCal: ' + fooResults.startMinCal) // This should log "1000" but won't until the object name inside `fooResults` is created correctly.

// 
console.log(Object.keys(foo)); // I believe this gests the property name, but it exists inside an array, so won't work as a new property name 
console.log(foo[Object.keys(foo)[0]]); // this gets the property value as expected.

更新的工作代码:

var foo = {
  startMin: 1000,
  startMax: 3000
};

var fooResults = {
  [Object.keys(foo)[0] + 'Cal']: foo[Object.keys(foo)[0]],
  [Object.keys(foo)[1] + 'Cal']: foo[Object.keys(foo)[1]]
}

console.log('startMinCal: ' + fooResults.startMinCal)
console.log('startMaxCal: ' + fooResults.startMaxCal)

1 个答案:

答案 0 :(得分:1)

var foo = {
  startMin: 1000
};


//Object.keys return all the keys in an object passed as parameter

//here your wanted key is at first position
var key = Object.keys(foo)[0];

//get the value
var value = foo[key]

//append whatever suffix you want
key += 'Cal';



var fooResults = {
  //to use  content of variable as key of object put variable  in []   
  [key]: value
}


//another solution 
//create emtyy object 
var fooResults2 = {}

//use use variable name as index
fooResults2[key] = value


console.log('startMinCal: ' + fooResults.startMinCal) // This should log "1000" but won't until the object name inside `fooResults` is created correctly.

console.log('startMinCal: ' + fooResults2.startMinCal)