简体   繁体   中英

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM