I have this js object data:
const content =
[ { h1 : 'This is title number 1' }
, { h2 : 'Description' }
, { p : 'Description unique content text' }
, { h2 : 'Content' }
, { p : 'Content unique text here 1' }
, { ul : [
'string value 1',
'string value 2'
]
, }
, { p : 'Content unique text here 2' }
, { h2 : 'CTA message' }
, { p : 'CTA message unique content here' }
, { h2 : 'CTA button' }
, { p : 'CTA button unique content here' }
, { p : '' }
, { h1 : 'This is title number 2' }
, { h2 : 'Description' }
, { p : 'Description unique content text' }
, { h2 : 'Content' }
, { p : 'Content unique text here 1' }
, { h2 : 'CTA message' }
, { p : 'CTA message unique content here' }
, { h2 : 'CTA button' }
, { p : 'CTA button unique content here' }
, { p : '' }
]
h1
indicates a new object, the ul
is optional
I want to map it to such structure:
interface Content = {
title: string;
description: string;
content: any[];
cta: {
message: string;
button: string;
}
}
I am wondering what is the best way of doing that?
I think I have to loop through the items and just populate a new JSON object based on my interface. The first element is always title, then just checking if "description" then the next item is description value.
const json = Content[];
content.forEach(element => {
if(element.h1) {
// add props to new object
// add object to json array
}
});
I just wonder how wold you create multiple Content objects based on that original content JSON object?
Here is the result I am expecting:
json = [
{
title: 'This is title number 1',
description: 'Description unique content text',
content: [
{
p: 'Content unique text here 1',
},
{
ul: [
'string value 1',
'string value 2'
]
},
{
p: 'Content unique text here 2'
}
],
cta: {
message: 'CTA message unique content here'
button: 'CTA button unique content here'
}
},
...
]
UPDATE:
Based on comments below I am looking for top down parser solution. The solution should be easily extensible in case if input array will be changed a bit by introducing new unique h2+p
or h2+p+ul
, etc elements.
abc
`, but it doesn't. `{p: "abc"}` means ` – Rashad Saleh Jun 21 '22 at 13:39