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?
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)