简体   繁体   中英

Update Array containing objects using spread operator

I have an array containing objects in javascript / typescript.

let array = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}]

How can I update name of the second element (with id 2) and copy the array to a new array using javascript spread (...) operator?

You can use a mix of .map and the ... spread operator

You can set the value after you've created your new array

 let array = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}]; let array2 = array.map(a => {return {...a}}) array2.find(a => a.id == 2).name = "Not Two"; console.log(array); console.log(array2);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

Or you can do it in the .map

 let array = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}]; let array2 = array.map(a => { var returnValue = {...a}; if (a.id == 2) { returnValue.name = "Not Two"; } return returnValue }) console.log(array); console.log(array2);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

There are a few ways to do this. I would suggest using Array.map :

let new_array = array.map(element => element.id == 2 ? {...element, name : 'New Name'} : element);

or with Object.assign :

let new_array = array.map(element => element.id == 2 ? Object.assign({}, element, {name : 'New Name'}) : element);

Map returns a new array, so you shouldn't need the array spread operator.

We can use

let array = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}];
let array2 = [...array]
array2.find(a => a.id == 2).name = "Not Two";
console.log(array2);

You can simply use map() and change the element there. here is the code---

array_copy = array.map((element) => {
  console.log(element.id);
  if (element.id === 2) {
    element.name = "name changed";
  } 
return element;
});

console.log(array_copy);

Here the main array also gets modified, as elements inside the array are objects and it references to the same location even in the new array.

You can do it like this in map , no need for spread :

const array = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}]

const updatedArray = array.map(a => {
   if (a.id == 2) {
      a.name = 'New Name';
   }
   return a;
});

Merging properties from filterQueryParams to selectedLaws (existing solutions did not suit me):

if (this.filterQueryParams && Object.prototype.toString.call(this.filterQueryParams) === '[object Array]') {
  for (const law of this.filterQueryParams) {
    if (law as Laws.LawDetail) {
      const selectedLaw = this.selectedLaws.find(x => x.languageCode === law.languageCode);
      if (selectedLaw) {
        for (const propName of Object.keys(law)) {
          selectedLaw[propName] = law[propName];
        }
      }
      else {
        this.selectedLaws.push(law);
      }
    }
  }
}

Using Spred Operator, you can update particular array value using following method

 let array = [ { id: 1, name: "One" }, { id: 2, name: "Two" }, { id: 3, name: "Three" }, ]; const label = "name"; const newValue = "Two Updated"; // Errow comes if index was string, so make sure it was integer const index = 1; // second element, const updatedArray = [ ...array.slice(0, index), { // here update data value ...array[index], [label]: newValue, }, ...array.slice(index + 1), ]; console.log(updatedArray);

import React,{useState} from 'react';


export function App(props) {
  const[myObject,setMyObject] = useState({
    "Name":"",
    "Age":""
  });
  const[myarray, setmyarray] = useState([]);
const addItem =() =>{
  setMyObject({...myObject,"Name":"Da","Age":"20"});
  setmyarray([...myarray, 1]);
};

  console.log(myarray);console.log(myObject);
  return (
    <div className='App'>
      <h1>Hello React.</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={addItem}>Add me</button>
    </div>

  );
}

// Log to console
console.log('Hello console')

 let array = [ { id: 1, name: "One", location: { lat: 23.2223, lng: 56.2214 } }, { id: 2, name: "Two", location: { lat: 23.2223, lng: 56.2214 } }, { id: 3, name: "Three", location: { lat: 23.2223, lng: 56.2214 } }, ]; 

I have this array like this what should I do? tell me please, above answer cannot mutate the location object.

 let array = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}]; let array2 =[...array.slice(0, 0), Object.assign({}, array[0], { name:'new one' //change any property of idx }),...array.slice(0 + 1)] console.log(array); console.log(array2);

[...array.slice(0, idx), Object.assign({}, array[idx], {
               x:new_x  //change any property of idx
        }),...array.slice(idx + 1)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM