This is one of the problem I have encountered during my latest project at work. So basically, I have a huge object contained a lot of keys and values of different contexts that were going to be used for multi-language on an mobile app
const object = {
title.welcome: "Hello",
content.welcome: "Welcome to the app",
button.welcome: "Click here to start"
}
These values are the default values, and they can be changed. Let's assume the object is changed like this:
const object = {
title.welcome: "Welcome",
content.welcome: "This is your first step of using the app",
button.welcome: "Continue"
}
And what I had to do in the project was to create a default value so that the admin can change the value back to the default ones. The default values was stored as an array of string like this:
const defaultValues = ["Hello", "Welcome to the app", "Click here to start"]
// same values as the default object
Long story short, I had to combine the object and the array into this array of object:
const arrayOfObjects = [
{
key: "title.welcome",
value: "Welcome",
default: "Hello"
},
{
key: "content.welcome",
value: "This is your first step of using the app",
default: "Welcome to the app"
},
{
key: "button.welcome",
value: "Click here to start",
default: "Continue"
},
]
So, I wrote a function that takes an object and array and return an array of objects like above. And also in this situation, the order of the elements in the array is the same as the the order of the key value pairs in the object. Full code snippets of this example:
const object = {
title.welcome: "Welcome",
content.welcome: "This is your first step of using the app",
button.welcome: "Continue"
};
const defaultValues = ["Hello", "Welcome to the app", "Click here to start"];
const combineObjectWithArray = (object, array) => {
const arrayOfObjects = [];
let newObject = {};
for (let [key, value] of Object.entries(object)) {
const index = Object.keys(object).indexOf(key);
newObject = {
key,
value,
default: array[index]
};
arrayOfObjects.push(newObject);
};
return arrayOfObjects;
};
console.log(combineOjectWithArray(object, defaultValues));
Comments (0)