Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

134
Views
Basic Stringify question with call back function

So I just started learning json and have a question.

const rabbit = {
  name: 'BobJ',
  color: 'black',
  size: null,
  birthDate: new Date(),
  jump: () => {
    console.log(`${name} can jump!`);
  }
}

json = JSON.stringify(rabbit, (key, value) => {
  console.log(`key: ${key}, value: ${value}`);
  return key === 'name' ? 'Elsa' : value;
});
console.log(json)

this *return key === 'name' ? 'Ellie' : value;* part means if there is a 'name' key, set the value to Ellie, else return its original value.

What if I wanted to have more then 2 keys in that code? like name and color? how would the code look like?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You could put multiple if else condition.

if (key === 'name') {
 return 'Elsa'
} else if (key === 'color') {
  return 'Green'
} 
// if nothing else
return value

You could also use a switch statement. Or a nested ternary.

I like to use a hashmap/object for this.

const rabbit = {
  name: 'BobJ',
  color: 'black',
  size: null,
  birthDate: new Date(),
  jump: () => {
    console.log(`${name} can jump!`);
  }
}

const keyMap = {
  name: "Elsa",
  color: "Green",
}

json = JSON.stringify(rabbit, (key, value) => {
  console.log(`key: ${key}, value: ${value}`);
  return keyMap[key] || value
});

console.log(json)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!