Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

207
Views
add multiple objects to an array of objects at a certain index

I have an array that looks similar to this,

[
    { 'name': 'Bob', 'age': 25, 'sex': 'M' },
    { 'name': 'Gill', 'age': 33, 'sex': 'F' },
    { 'name': 'Glen', 'age': 55, 'sex': 'M' },
    { 'name': 'Flo', 'age': 19, 'sex': 'F' }
]

I have another array of objects that looks like this,

[
    { 'name': 'Fred', 'age': 49, 'sex': 'M' },
    { 'name': 'Thelma', 'age': 27, 'sex': 'F' }
]

I want to add this second of objects to my first array so the first array would look like this,

[
    { 'name': 'Bob', 'age': 25, 'sex': 'M' },
    { 'name': 'Fred', 'age': 49, 'sex': 'M' },
    { 'name': 'Thelma', 'age': 27, 'sex': 'F' }
    { 'name': 'Gill', 'age': 33, 'sex': 'F' },
    { 'name': 'Glen', 'age': 55, 'sex': 'M' },
    { 'name': 'Flo', 'age': 19, 'sex': 'F' }
]

So I thought it would be case of doing,

originalPeople.splice(1, 0, newPeople)

But when I console.log my originalPeople array doing this, I get the following similar output,

{ 'name': 'Bob', 'age': 25, 'sex': 'M' },
    ƒ newPeople(),
    { 'name': 'Gill', 'age': 33, 'sex': 'F' },
    { 'name': 'Glen', 'age': 55, 'sex': 'M' },
    { 'name': 'Flo', 'age': 19, 'sex': 'F' }

I assume you can splice an array objects into an array and I have to do something different?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Use spread operator to add newPeople (see code below)

let originalPeople = [
    { 'name': 'Bob', 'age': 25, 'sex': 'M' },
    { 'name': 'Gill', 'age': 33, 'sex': 'F' },
    { 'name': 'Glen', 'age': 55, 'sex': 'M' },
    { 'name': 'Flo', 'age': 19, 'sex': 'F' }
]

let newPeople = [
    { 'name': 'Fred', 'age': 49, 'sex': 'M' },
    { 'name': 'Thelma', 'age': 27, 'sex': 'F' }
]

originalPeople.splice(1, 0, ...newPeople)

console.log(originalPeople)
about 4 years ago · Juan Pablo Isaza Report

0

could this be useful?

var arr1 = [
    { 'name': 'Bob', 'age': 25, 'sex': 'M' },
    { 'name': 'Gill', 'age': 33, 'sex': 'F' },
    { 'name': 'Glen', 'age': 55, 'sex': 'M' },
    { 'name': 'Flo', 'age': 19, 'sex': 'F' }
]

var arr2 = [
    { 'name': 'Fred', 'age': 49, 'sex': 'M' },
    { 'name': 'Thelma', 'age': 27, 'sex': 'F' }
]

arr1.push(...arr2);

console.log(arr1)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!