繁体   English   中英

使用扩展运算符更新包含对象的数组

[英]Update Array containing objects using spread operator

我有一个包含 javascript / typescript 中的对象的数组。

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

如何更新第二个元素的名称(id 为 2)并使用 javascript spread (...) 运算符将数组复制到新数组?

您可以混合使用.map...扩展运算符

您可以在创建新数组后设置值

 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; }

或者您可以在.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; }

有几种方法可以做到这一点。 我建议使用Array.map

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

或使用Object.assign

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

Map 返回一个新数组,因此您不需要数组扩展运算符。

我们可以用

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);

您可以简单地使用map()并在那里更改元素。 这是代码---

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

console.log(array_copy);

这里主数组也被修改,因为数组中的元素是对象,即使在新数组中它也引用相同的位置。

您可以在map中这样做,无需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;
});

filterQueryParams中的属性合并到selectedLaws (现有解决方案不适合我):

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);
      }
    }
  }
}

使用 Spred 运算符,您可以使用以下方法更新特定数组值

 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 } }, ]; 

我有这样的阵列,我该怎么办? 请告诉我,上面的答案不能改变位置对象。

 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)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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