Search code examples
javascriptarraysobjectsemantic-ui-react

Create a new array of objects by inserting tags


I want to change this array of objects:

const arr = [
   {title: "Title 1", content: ["Lorem", "ipsum", "dolor"]},
   {title: "Title 2", content: ["Lorem", "ipsum", "dolor"]},
   {title: "Title 3", content: ["Lorem", "ipsum", "dolor"]},
   {title: "Title 4", content: ["Lorem", "ipsum", "dolor"]}
]

to this format:

const newArr = [
                {
                  title: "<Label color='blue' content='Title 1' />", 
                  content: [
                           "<Message content='Lorem'/>", 
                           "<Message content='ipsum'/>", 
                           "<Message content='dolor'/>"
                          ]
                },
                ....
                ....
                {
                  title: "<Label color='blue' content='Title 4' />", 
                  content: [
                             "<Message content='Lorem'/>", 
                             "<Message content='ipsum'/>", 
                             "<Message content='dolor'/>"
                           ]
                },
               ]

Just in case you want to know why, I'm trying to integrate an accordion component from semantic-ui-react. Check this out.


Solution

  • I gave it a shot and I think this is what you're looking for:

    const arr = [
       {title: "Title 1", content: ["Lorem", "ipsum", "dolor"]},
       {title: "Title 2", content: ["Lorem", "ipsum", "dolor"]},
       {title: "Title 3", content: ["Lorem", "ipsum", "dolor"]},
       {title: "Title 4", content: ["Lorem", "ipsum", "dolor"]}
    ];
    
    const newArr = arr.map(function(obj) {
      return {
        title: "<Label color='blue' content='" + obj.title + "'/>",
        content: obj.content.map(function(c) {
          return "<Message content='" + c + "'/>";
        })
      };
    });
    
    console.log(newArr);