首页 > 解决方案 > 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)

标签: javascriptobjectproperties

解决方案


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)


推荐阅读