0

I got an array of objects like this:

const defaultActors = 
[
  {
   data: {name: "name1"}
  },
  {
   data: {name: "name2"}
  }
]

and a simple array like this:

   const actorsToBeAdded = ["nameX", "nameY"]

Is there an easy way to get this:

 const combinedActors =  [
      {
       data: {name: "name1"}
      },
      {
       data: {name: "name2"}
      },
      {
       data: {name: "nameX"} //newly added
      },
      {
       data: {name: "nameY"} //newly added
      }
    ]

I'm using useState and trying to get combined array of objects like this:

    setCombinedActors(
    actorsToBeAdded.map((actor) => 
      ({
        data: {name : actor} //data from [nameX, nameY] array
        //also need to spread data from {name: "name1" ...} array
       })
     )
   )

EDIT: thanks for answers. Concat does result in one array but it's array of both "direct" values and objects, like this

["name1", "name2", {Object_with_data},{Object_with_data}]

is there a way to get

[{Object_with_data},{Object_with_data}, {Object_with_data},{Object_with_data}]

or this

["name1", "name2", "name3", "name4"]

? I created sandbox: https://codesandbox.io/s/epic-taussig-zeyev?file=/src/App.js

Thanks to anyone interested!

2 Answers 2

1

You can just concat both arrays using Array.prototype.concat like:

setCombinedActors(
    defaultActors.concat(
        actorsToBeAdded.map(actor => ({ data: { name : actor } }))
    )    
)

Also you may want to add only the actors that are still not in the defaultActors array, for that you can use a filter like:

setCombinedActors(
    defaultActors.concat(
        actorsToBeAdded
            .filter(actor => !defaultActors.some(({ data }) => data.name === actor))
            .map(actor => ({ data: { name : actor } }))
    )    
)

Answering the edit, if you want to conver all to String's.

arr.map(elm => typeof elm === 'string' ? elm : elm.data.name)

Otherwise, if you want objects.

arr.map(elm => typeof elm === 'string' ? { data: { name: elm } } : elm)

Note: Assuming all elements of the array are either a String or an object with the structure { data: { name: 'a string' } }.

Sign up to request clarification or add additional context in comments.

2 Comments

So you have an array with either objects or strings and you want to make it only strings or objects right?
Check edit to see if that was it. Just a reminder don't post multiple questions in a single post.
0
actorsToBeAdded.forEach(value=>{
defaultActors.push(
              {data:{name:value}},
              );
}
)

Try this out.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.