3

I want to replace the value in existing JSON object in Node.js

Code :

var designationName='Softwar Engineer';
console.log(generateData[0]);

Console Output:

{ 
email: '[email protected]',
designation: 10,
id: 274,
first_name: 'firstname',
mobile: '1234567890',
last_name: 'lastname'
}

In the above console output 'designation' value printed as '10'

Expected Result:

I want to replace "designation: Software Engineer" instead of "designation:10"

2
  • generateData[0].designation = designationName; ? Commented Feb 29, 2016 at 7:16
  • What has this got to do with JSON? There is no JSON in your example code. Commented Feb 29, 2016 at 9:46

2 Answers 2

3

Considering generateData[0] contains the following json which you fetch from a database

 { 
  email: '[email protected]',
  designation: 10,
  id: 274,
  first_name: 'firstname',
  mobile: '1234567890',
  last_name: 'lastname'
 };

To replace "designation: Software Engineer" instead of "designation:10"

var designationName = 'Software Engineer';
if(generateData[0]){
 generateData[0]['designation']= designationName;
}
console.log(generateData[0]);
Sign up to request clarification or add additional context in comments.

Comments

1
var designationName='Softwar Engineer';
if( generateData.length && generateData[0].designation)
{
    generateData[0].designation = designationName;
}
console.log(generateData[0]);

6 Comments

Hi DinhNC, Thanks for your answer, but out put was look like in the below. { email: '[email protected]', designation: 10, id: 274, first_name: 'Siva', mobile: '9942235226', last_name: 'Palaniappan' }
Hi DinhNC, Thanks for your answer, but output was look like in the below. as { desigantion:NaN}
Can you share your code please! I think your running don't correct. You can see example here: node-console.com/script/code Copy code below for testing: var generateData = [{ email: '[email protected]', designation: 10, id: 274, first_name: 'Siva', mobile: '9942235226', last_name: 'Palaniappan' }]; var designationName='Softwar Engineer'; generateData[0].designation = designationName; console.log(generateData[0]);
Your output was look like { desigantion:NaN}. Maybe storage structure type in DB don't correct or you try storing String into Number.
|

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.