0

I have some function:

function funcName(first_data, SECOND_DATA) {
    // ...some code here...
    data: {dontMatterProp: dontMatterVal, SECOND_DATA: SECOND_DATA},
    // ...some code.....
}

I need that my property name 'SECOND_DATA' changes too! for example in php a could do something like {SECOND_DATA}...

3
  • Try data[SECOND_DATA] = SECOND_DATA; Commented Jul 1, 2016 at 18:37
  • data[0] = SECOND_DATA works ok. But data[SECOND_DATA] = SECOND_DATA don't work Commented Jul 1, 2016 at 18:49
  • give me plase an example of SECOND_DATA value ! Commented Jul 1, 2016 at 18:50

2 Answers 2

2

Your question is a little unclear, but I think something like this is what you are looking for:

function funcName(first_data, SECOND_DATA_KEY, SECOND_DATA_VALUE) {
  // ...some code here...
  x = {}
  x.data = {dontMatterProp: dontMatterVal}
  x.data[SECOND_DATA_KEY] = SECOND_DATA_VALUE
  // ...some code.....
}

If you just want the key to be equal to the value, you could just do

x.data[SECOND_DATA] = SECOND_DATA

But that's a little odd. Why map something to itself? No value necessary, you can just verify that the key exists if that's the case...

You can use brackets for dynamic keys in javascript. So,

var x = {}
x['something'] = 'test'
// x === { 'something': 'test' }

x[something] = 'test2'
// error: something is undefined

var something = 'hello'
x[something] = 'test3'
// x === { 'something': 'test', 'hello': 'test3' }

Hope that helps?

Sign up to request clarification or add additional context in comments.

Comments

1

I think you want:

data[SECOND_DATA] = SECOND_DATA; // assign the value

If you just use:

var data = { SECOND_DATA: SECOND_DATA };

using object notation - the property name will ALWAYS be SECOND_DATA

2 Comments

He claimed that SECOND_DATA would be a string in the comments to his question.
Missed that... so yeah he wants to avoid object notation, and use data[ ... ] instead. (Not using { ... } )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.