2

I need to update the data inside the below state using spread operator. It has to be done such a way that data[0] should be updated with "vehOn":"Finance"

let state = {
  "data": [{
    "year": "2017",
    "make": "ALFA ROMEO",
    "model": "ILX 4D 2.0 PREMIUM PACKAGE"
  }],
  "error": ""
};

Modfied state should be like:

let modifiedstate = {
  "data": [{
    "year": "2017",
    "make": "ALFA ROMEO",
    "model": "ILX 4D 2.0 PREMIUM PACKAGE",
    "vehOn": "Finance"
  }],
  "error": ""
};
5
  • 1
    "I need to ... using spread operator" - Why? Please format your question/code properly? And what have you tried so far? Commented Dec 28, 2018 at 15:29
  • ...maybe...modifiedstate.data[0]["vehOn"]="Finance"??? Commented Dec 28, 2018 at 15:33
  • @gaetanoM I am trying to get it done using the spread operator. Commented Dec 28, 2018 at 15:37
  • @Andreas I have tried below implementation but didn't work as expected. :( let oldData = state.data[0]; let newData = {'vehOn':'finance'}; let mergedData = {... oldData, ...newData}; let mergedState1 = {...state.data, ...mergedData}; //Didn't work let mergedState2 = {...state, data:[...state.data,mergedData]}; //Didn't work Commented Dec 28, 2018 at 15:44
  • 1
    But why do you need to use the spread operator? if your intention is to clone state you should know that the spread operator does not make shallow copies. Commented Dec 28, 2018 at 15:46

3 Answers 3

1

As per documentation the only way I can see to achieve your result is:

let state = {
    "data": [{
        "year": "2017",
        "make": "ALFA ROMEO",
        "model": "ILX 4D 2.0 PREMIUM PACKAGE"
    }],
    "error": ""
};

let modifiedstate  = { "data": [{ ...state.data[0], ...{vehOn: "Finance"} }],
    "error": ""};

console.log(modifiedstate);

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

Comments

1

const state = {
  "data": [{
    "year": "2017",
    "make": "ALFA ROMEO",
    "model": "ILX 4D 2.0 PREMIUM PACKAGE"
  }],
  "error": ""
};

console.log("---- state ----");
console.log(state);

const modifiedstate = { ...state,
  data: state.data.map((entry, i) => i === 0 ? ({ ...entry,
    vehOn: "Finance"
  }) : entry)
};

console.log("---- modifiedstate ----");
console.log(modifiedstate);

Comments

0

If your intention is to create an object that is identical to state and you don't know what properties state can have you should look for a way to deep clone it

Otherwise if you are absolutely sure of the structure of state and want to do a simple clone you can do the following:

   let modifiedstate = "data": [{
     ...state.data[0],
     "vehOn": "Finance"
     }],
     "error": ""
   }

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.