I have data like this:
const currentData = {
id: "u76u76h",
type: "cardA",
name: "Section 1",
thumbnail: {
src: "",
alt: "",
},
data: {
avatar: {
dataType: "image",
src: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBXgFy56y56y56",
alt: "avatar"
},
album: [
{
dataType: "image",
src: "https://firebasestorage.googleapis.com/album_image1.png",
alt: "album_image1"
},
{
dataType: "image",
src: "https://firebasestorage.googleapis.com/album_image2.png",
alt: "album_image2"
}
],
cards: [
{
icon: {
dataType: "image",
src: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBXgF",
alt: "card_image1"
},
title: "新規事業企画担当",
description: [
"企画書だけでは、「新しいビジネスの良さを理解してもらう事」が難しい!",
"アイディアを実際に使ってもらって実感してもらいたい!"
]
}
]
}
};
I want to extract all the base64 urls (none https) and upload to cloud storage, and after uploaded the storage I want to update the uploaded urls to the data object above before saving the data object to the database. But the problem is the data structure is complicated and can be 2 or 3 or more in nested level. I am scratching my head to find a solution. Please help me!
You can use recursion to view the whole object. Be careful if the object contains circular references.
And remove isBase64Fake function. Use isBase64 instead. I've added isBase64Fake only to check your object.
function extractBase64(data) {
const result = [];
Object.keys(data).forEach((key) => {
if (typeof data[key] === 'string') {
isBase64Fake(data[key]) && result.push({
data,
key,
value: data[key]
});
} else if (typeof data[key] === 'object') {
result.push(...extractBase64(data[key]));
}
});
return result;
}
function uploadSomewhere(dataToUpload) {
console.log('uploading...');
setTimeout(() => {
dataToUpload.forEach((item) => {
item.data[item.key] = 'QWERTY';
});
}, 1000);
}
function isBase64Fake(str) {
return /^data:/.test(str);
}
function isBase64(str) {
if (!str) {
return false;
}
try {
window.atob(base64);
result = true;
} catch (e) {
result = false;
}
}
const currentData = {
id: "u76u76h",
type: "cardA",
name: "Section 1",
thumbnail: {
src: "",
alt: "",
},
data: {
avatar: {
dataType: "image",
src: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBXgFy56y56y56",
alt: "avatar"
},
album: [{
dataType: "image",
src: "https://firebasestorage.googleapis.com/album_image1.png",
alt: "album_image1"
},
{
dataType: "image",
src: "https://firebasestorage.googleapis.com/album_image2.png",
alt: "album_image2"
}
],
cards: [{
icon: {
dataType: "image",
src: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBXgF",
alt: "card_image1"
},
title: "新規事業企画担当",
description: [
"企画書だけでは、「新しいビジネスの良さを理解してもらう事」が難しい!",
"アイディアを実際に使ってもらって実感してもらいたい!"
]
}]
}
};
const dataToUpload = extractBase64(currentData);
console.log(dataToUpload);
uploadSomewhere(dataToUpload);
setTimeout(() => console.log(currentData), 2000);