1

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

1
  • Why use the spread operator for the first case? To add multiple states at once? Commented Apr 18, 2022 at 9:25

2 Answers 2

3

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)

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

Comments

2

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)

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.