javascript - How can I get the name of a property from inside an object to create a new property name?
问题描述
I know there are a few other posts on this topic, but they don't seem to address my issue: link.
I want to be able to dynamically get the name of a specific property in an object so that I can use it to create a new property name inside another object. For example, I would get the property name startMin
from foo
(as in my code below) and then add text to the end of it (like startMin + Suffix
) to create a new property name. How can I do this?
A related note: I've already figured out how to get the property value with foo[Object.keys(foo)[0]]
. Though this works, I'm not sure why Object.keys
gets the property value in this case since the examples I've found suggest Object.keys
is supposed to get the property name not the property value. I'd love to know why?
I have included the pusdo code foo[Object.returnObjectName(foo)[0]] + 'Cal'
where I want the name to be dynamically created. It doesn't work, of course.
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.
UPDATED WORKING CODE:
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)
解决方案
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)
推荐阅读
- python - Pandas loc 使用包含范围,而 iloc 在上侧使用独占
- c# - Azure Functions on Consumption Plan 是否使用多个服务器?
- flutter - 在 Flutter SDK 中将通道从 Stable 更改为 Master 时出现 Powershell 问题
- nlp - 在项目符号和编号处拆分句子?
- javascript - JS 中的全局作用域到底是什么?
- python - 散景 1.4.0 胡须未显示
- c++ - 我不知道我的 c++ 代码有什么问题,因为没有出现警告
- c# - C# 授予注册表权限
- ios - SwiftUI:点击 TabView 的选项卡时崩溃
- apache-nifi - 从 Git 恢复 Nifi 注册表