2

This is my code

var data={};

data={stdId:"101"};
data={empId:"102"};
data={deptId:"201"};

I have a data object getting data from services with one key only. but key names are different like stdId or empId ,etc.
I want to assign empty value to stdId or empId ,etc. like data={stdId:""} .
The key names are changed dynamically based on services.

1
  • How are you planning to use this kind data in your application even if you achieve just to make key value as null? Commented Mar 8, 2016 at 14:00

4 Answers 4

4

Not entirely sure what you are trying to achieve, but if you know the name of the property you could use:

data['stdId'] = '';

or

data.stdId = '';

If you do not know the property name, but you still want to keep the property names on the object you could use:

for(var prop in data) {
  if(data.hasOwnProperty(prop)) {
    data[prop] = '';
  }
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can use for..in loop to iterate over data object using key.

for(var key in data){
  if(data.hasOwnProperty(key)){
     data[key] = '';
  }
}

Note: This will set every property of data object to ''

Comments

0
data.stdId = null;

or

data.stdId = '';

or

data = { stdId };

Have you tried those?

Comments

0

As I understand your question, you won't know the name of the key in each object and there is only ever one. To solve your problem:

data[Object.keys(data)[0]] = ''

This will assign the value of the key to null.

Comments

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.