Javascript 使用find方法更改typescript中所有元素的类数组属性值

Javascript 使用find方法更改typescript中所有元素的类数组属性值,javascript,typescript,Javascript,Typescript,我在下面有一个示例代码 let arr = [ { name:"string 1", value:"value1", other: "other1" }, { name:"string 2", value:"value2", other: "other2" } ]; let obj = arr.find((o, i) => { arr[i] = { name: 'new name', value: 'new value', other: 'that' }; retu

我在下面有一个示例代码

let arr = [
{ name:"string 1", value:"value1", other: "other1" },
{ name:"string 2", value:"value2", other: "other2" }
];

let obj = arr.find((o, i) => {
       arr[i] = { name: 'new name', value: 'new value', other: 'that' };
    return true; // stop searching
});

  console.log(arr);
我想用名称“new name”和值“new value”替换所有数组值,现在它只更改第一个数组索引值。

find()
返回与条件匹配的数组的第一个元素。您正在从函数返回
true
,因此它在第一个索引之后停止迭代

当您必须将数组的每个值更改为新值时。您应该使用
map()
。从
map()
函数返回并删除对象。首先使用spread oeprator
将对象的所有属性复制到最终对象中,然后将所需属性设置为新值

让arr=[
{name:“string 1”,value:“value1”,other:“other1”},
{name:“string 2”,value:“value2”,other:“other2”}
];
const res=arr.map(x=>({…x,名称:“新名称”,值:“新值”}))

console.log(res)
如果您不想创建新数组,而是修改
arr
本身,那么您可以像这样使用forEach:

让arr=[
{name:“string 1”,value:“value1”,other:“other1”},
{name:“string 2”,value:“value2”,other:“other2”}
];
arr.forEach((元素)=>{
element.name='新名称';
element.value='新值';
element.other='that';
})

控制台日志(arr)@PiushShukla不客气。在创建项目之前,最好阅读一些关于所有数组方法的文档,特别是迭代方法。这对你有很大帮助。您可以在此处获得一个列表。还有一个问题是,如果需要根据条件更改值,如何应用筛选器。this.state.formOrderItems.map(x=>(x.id==ev?{…x,isDefault:checked}:x@PiushShukla上面的方法有什么问题?没什么,只是我需要根据条件过滤数据的条件之一。