I need to change this array of objects so that the strings are turned into numbers and the arrays are turned into something I can interate through. Im trying to make a table out of this. Heres what I tried so far:
function ParseData(obj) {
const keys = Object.keys(obj);
for (let i = 0; i < keys.length; i++) {
obj[keys[i]] = JSON.parse(obj[keys[i]]);
}
}
console.log(ParseData(newData));
const newData = [
{
apac: "[\"CN\",\"JP\"]"
brand: '1',
brands: '1183',
},
{
apac: "[\"CN\",\"JP\"]"
brand: '1',
brands: '1183',
},
];
Just loop through the array, and use ParseData function to update keys of each object in the array.
You dont have to return a value from the function, if you are updating the paramater itself. All the changes made to the parameter will be available in the newData variable.
const newData = [
{ apac: "[\"CN\",\"JP\"]", brand: '1', brands: '1183' },
{ apac: "[\"CN\",\"JP\"]", brand: '1', brands: '1183' },
];
function ParseData(myArray) {
myArray.forEach((node) => {
const keys = Object.keys(node);
for (let i = 0; i < keys.length; i++) {
node[keys[i]] = JSON.parse(node[keys[i]]);
}
})
}
ParseData(newData);
console.log(newData)
If you want to make your newData unchanged and ParseData function return a new variable, you could store your paramater in a variable an a shallow copy. I used JSON.parse(JSON.stringify(myArray)) for that.
Working Fiddle
const newData = [
{ apac: "[\"CN\",\"JP\"]", brand: '1', brands: '1183' },
{ apac: "[\"CN\",\"JP\"]", brand: '1', brands: '1183' },
];
function ParseData(myArray) {
const clonedata = JSON.parse(JSON.stringify(myArray));
clonedata.forEach((node) => {
const keys = Object.keys(node);
for (let i = 0; i < keys.length; i++) {
node[keys[i]] = JSON.parse(node[keys[i]]);
}
})
return clonedata;
}
const output = ParseData(newData);
console.log(newData);
console.log(output);
newData is not an object, it is an array of objects, so you don't need to use Object.keys(). Also your function doesn't return a value so your console log won't output anything.
Since keys within your objects are always the same you can do this:
const newData = [
{
apac: "[\"CN\",\"JP\"]",
brand: '1',
brands: '1183',
},
{
apac: "[\"CN\",\"JP\"]",
brand: '1',
brands: '1183',
},
];
function ParseData(arr) {
for (let i = 0; i < arr.length; i++) {
obj[i]['apac'] = JSON.parse(obj[i]['apac']);
obj[i]['brand'] = parseInt(obj[i]['brand']);
obj[i]['brands'] = parseInt(obj[i]['brands']);
}
return arr
}
console.log(ParseData(newData));
Try this one you get your output
<script>
const newData = [
{
apac: "[\"CN\",\"JP\"]",
brand: '1',
brands: '1183',
},
{
apac: "[\"CN\",\"JP\"]",
brand: '1',
brands: '1183',
},
];
function ParseData(obj) {
const keys = Object.keys(obj);
for (let i = 0; i < keys.length; i++) {
var b=JSON.stringify(obj[keys[i]]);
str = b.replace(/\\/g, '');
obj[keys[i]] = str;
}
return obj;
}
console.log(ParseData(newData));
</script>