1

I'm struggling with how to add the element of the array into an array of objects. I have an array of object:

0: (20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
1: (20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
2: (20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
...etc

And I have an array that contains strings:

const titles = ["some title A", "some title B", "some title C"]

So my purpose is, I want to make my data like this:

[
 {results: my_existing_array_of_object, title: "some title A"},
 {results: my_existing_array_of_object, title: "some title B"},
 {results: my_existing_array_of_object, title: "some title C"},
]

How to do that? Thanks in advance

1
  • 1
    titles.map((title) => ({results: resultsArray, title})); ? Commented Mar 26, 2021 at 17:58

2 Answers 2

1

I do some adjustment from the answer of @StepUp

const titles = ["some title A", "some title B", "some title C"]
const other = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }]

const result = other.map(((o, i) => ({results: o,      //add new key
    title: (i < titles.length) ? titles[i]  : ''})))
console.log(result )

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

Comments

1

It is possible to use map function to get desired array:

const titles = ["some title A", "some title B", "some title C"]
const other = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }]

const result = other.map(((o, i) => ({results: o, 
    title: (i < titles.length) ? titles[i]  : ''})))
console.log(result )

1 Comment

Thank you so much it works for me, and I do some adjustments because I need a new key. [link] (stackoverflow.com/a/66822377/14750244)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.