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

99
Views
add new elements to object just using spread

I have an object of states like below code. I want to add many states and cities to it

const stateObject = {
    missouri: ["springfield", "rolla"],
    nevada: ["carlin", "vegas"],
}

const addState = (...state) => {
    return stateObject.push(state);
}

I did not get answer.

  • How can I create a function to add new state to the object using the spread operator?
  • How can I create a function to add list of new city to one of state using the spread operator?

any solution would be much appreciated

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

0

Try this

const stateObject = {
    missouri: ["springfield", "rolla"],
    nevada: ["carlin", "vegas"],
}

const addState = (...states) => {
    states.forEach(state => stateObject[state] = []);
}

const addCity = (state, ...cities) => {
    stateObject[state] = [...stateObject[state], ...cities];
}

// test
addState('California', 'Texas')
addCity('California', 'Los Angeles')
addCity('Texas', 'Austin', 'Houston')
console.log(stateObject)

about 4 years ago · Juan Pablo Isaza Report

0

You can do it like this

const stateObject = {
    missouri: ["springfield", "rolla"],
    nevada: ["carlin", "vegas"],
}

const addState = (obj, ...states) => {
    states.forEach(state => obj[state] = [])
}

addState(stateObject, "NewYork", "Washington", "morestates")

console.log(stateObject)

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!