'Map Object Values to Another Object with Specific Model Typescript
I have an array of objects that I receive from API that looks like this:
Array [
Object {
"OPTIONNUMBER": "1",
"OPTIONVALUE": "Here is your name ",
},
Object {
"OPTIONNUMBER": "2",
"OPTIONVALUE": "Footer",
},
Object {
"OPTIONNUMBER": "3",
"OPTIONVALUE": "https://google.com",
},
]
how to map it to an object with a specific name as [OPTIONNAME]: OPTIONVALUE;
the model looks like this:
export interface IOptions {
opt1NAME: string;
opt2FOOTER_TEXT: string;
opt3LINK: string;
}
the end result should be like this:
const options = {
opt1NAME: 'Here is your name';
opt2FOOTER_TEXT: 'Footer';
opt3LINK: 'https://google.com';
}
I am trying map and assign but can't come up on how to properly map the names of the objects.
edit1:
//appOptions here is an array of string that contains names
let options = {};
for (let i = 0; i < appOptions.length; i++) {
Object.assign(options, {[appOptions[i]]:arr[i].OPTIONVALUE });
}
this works as giving me the right object but it not typed correctly.
Solution 1:[1]
try this
const options = [];
const op = ["opt1Name","opt2FOOTER_TEXT","opt3LINK"]
// you can list all your needed options in op and it will work
for (let index = 0; index < x.length; index+=3) {
const option:{[key:string]:any} = {};
// x is the name of your api result
const elements = x.slice(index,index+3);
elements.forEach((ele,idx)=>{
option[op[idx]]=ele.OPTIONVALUE
})
options.push(option)
}
Solution 2:[2]
the solution was to create an empty object with empty content (it will be used for context anyways):
export const initOptions: IOptions = {
opt01FOOTER: '',
opt02FOOTER_TEXT: '',
opt03LINK: '',
}
then in function where we want to restructure:
let options: IOptions = initOptions;
const keys = Object.keys(options) as Array<keyof IOptions>;
//arr is the array with names and values
for (let i = 0; i < arr.length; i++) {
//Object.assign() works here as well
options[keys[i]] = arr[i].OPTIONVALUE;
}
now we can easily use options with descriptive names:
console.log(options.opt02FOOTER_TEXT);
if the number of options increases, we have to add one more entry to model and one empty key-value pair to the initOptions
I was trying to find a solution around the creation of empty object, open for better solution with typed options
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | denistepp |
