【问题标题】:class array property value change using find method for all the elements in typescript [duplicate]使用find方法对打字稿中的所有元素更改类数组属性值[重复]
【发布时间】:2020-02-27 06:43:40
【问题描述】:

下面有一个示例代码

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

我想用名称“新名称”和值“新值”替换所有数组值,现在它只更改第一个数组索引值。

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

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

    当您必须将数组的每个值更改为新值时。你应该使用map()。从map() 函数返回和对象。首先使用扩展操作符...将对象的所有属性复制到最终对象中,然后将所需的属性设置为新值

    let arr = [
    { name:"string 1", value:"value1", other: "other1" },
    { name:"string 2", value:"value2", other: "other2" }
    ];
    
    const res = arr.map(x => ({...x, name: "new name", value: "new value"}))
    
    console.log(res)

    【讨论】:

    • @PiushShukla 欢迎您。在制作项目之前,最好阅读一些关于所有数组方法的文档,特别是迭代方法。这会对你有很大帮助。您可以在此处获取列表developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    • 还有一个问题,如果我们需要根据条件更改值,如何应用过滤器。
    • this.state.formOrderItems.map(x => (x.id === ev ? { ...x, isDefault: checked } : x
    • @PiushShukla 上述方法有什么问题?
    • 没什么,但是我需要根据条件过滤数据的条件之一。
    【解决方案2】:

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

    let arr = [
        { name:"string 1", value:"value1", other: "other1" },
        { name:"string 2", value:"value2", other: "other2" }
        ];
        
        arr.forEach((element) => {
        	element.name = 'new name';
        	element.value = 'new value';
        	element.other = 'that';
        })
        console.log(arr);

    【讨论】:

      猜你喜欢
      • 2020-07-25
      • 2023-01-25
      • 1970-01-01
      • 2014-03-19
      • 1970-01-01
      • 2015-06-26
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      相关资源
      最近更新 更多