I’m trying to print a object in comma seperated strings format. but I’m unable to understand how to concat keys for objects. Here is an example.
let obj = {
"name": "Family",
"count": 6,
"Children": {
"name": "Jim",
"age": "24",
"address": {
"street": "5th ave",
"state": "NY",
"country":"US"
}
},
"parents": {
"name": "John",
"age": "45",
"address": {
"street": "New brew st",
"state": "CA",
"country":null
}
}
};
let data = '';
let tempKey = '';
function printValues(obj) {
for (var key in obj) {
if (typeof obj[key] === "object") {
printValues(obj[key]);
} else {
data += key + ' - ' + obj[key] + ',';
}
tempKey = '';
}
return data;
}
console.log(printValues(obj));
Here my target is to get the output below format.
"name – Family,count – 6,Children_name – Jim,Children_age –
24,Children_address_street – 5th ave,Children_address_state –
NY,Children_address_country – US,parents_name – John,parents_age –
45,parents_address_street – New brew st,parents_address_state –
CA,parents_address_country – null"
my current output is
"name – Family,count – 6,name – Jim,age – 24,street – 5th ave,state –
NY,country – US,name – John,age – 45,street – New brew st,state – CA,"
I’m a bit confused about how to do this.
>Solution :
You should keep track of the parent property name on your recursive calls so that you’ll append that prefix if any was passed.
Here I added that argument to your function and I use it to compose the key string used when you "serialize" your object.
I used template literals to make string composition:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
let obj = {
"name": "Family",
"count": 6,
"Children": {
"name": "Jim",
"age": "24",
"address": {
"street": "5th ave",
"state": "NY",
"country":"US"
}
},
"parents": {
"name": "John",
"age": "45",
"address": {
"street": "New brew st",
"state": "CA",
"country":null
}
}
};
let data = '';
let tempKey = '';
function printValues(obj, parent = '') {
for (var key in obj) {
if (typeof obj[key] === "object") {
printValues(obj[key], `${parent}${key}_`);
} else {
data += `${parent}${key}` + ' - ' + obj[key] + ',';
}
tempKey = '';
}
return data;
}
console.log(printValues(obj));