add new elements to object just using spread

Viewed 332

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

2 Answers

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)

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)

Related