简体   繁体   English

如何用for循环修改对象键更具声明性?

[英]How to be more declarative with for loop modify object key?

I want to search through an existing object and modify its property. 我想搜索现有对象并修改其属性。 This works great: 这很好用:

function changeObjectKey(targetObject) {
       for(var i = 0; i < listofobjects.length; i++) {
          if(targetobject.keyone == listofobjects[i].keyone) 
            listofobjects[i].keytwo = 'changedvalue';
            break;
          }
        }
}

I want to make it smarter using filter, how can I do that? 我想使用过滤器使其更智能,该怎么做? I tried: 我试过了:

function changeObjectKey(targetObject) {
let filteredobject = listofobjects.filter(function(currentobject) {
return (currentobject.keyone == targetobject.keyone);
 });
filteredobject.keytwo = 'changedvalue';

} }

Note: Only a single object will match in the filter. 注意:过滤器中将仅匹配一个对象。 Though the latter is not changing listofobjects.keytwo... but I think a copy of it. 尽管后者不会更改listofobjects.keytwo ...,但我认为是它的一个副本。 Whereas in the first case, the original listofobjects[i].keytwo is being changed. 而在第一种情况下,原始对象[i] .keytwo的列表将被更改。

What is the correct way to do this? 正确的方法是什么?

Just take the first [0] : 只需取第一个[0]

let filteredobject = listofobjects.filter(function(currentobject) {
return (currentobject.keyone == targetobject.keyone);
 })[0];
filteredobject.keytwo = 'changedvalue';

I guess map would be a better fit for this. 我想map会更适合这个。 Of course you could chain the map after a filter . 当然,您可以在filter之后链接map

Also, I have not mutated the original object. 另外,我还没有突变原始对象。 If that is something you want to do you could do that. 如果那是您想做的事情,那么您可以这样做。 But generally, you do not use these function ( map , filter , reduce ) to mutate data. 但是通常,您不使用这些功能( mapfilterreduce )来变异数据。

function changeObjectKey(targetObject) {
  return listofobjects.map(function (obj) {
    if (obj.keyone !== targetobject.keyone) {
      return obj;
    }

    return Object.assign({}, obj, {
      keytwo = 'changedvalue'
    })
  })
}

I think is better the map() method. 我认为更好的map()方法。

The map() method creates a new array with the results of calling a provided function on every element in this array. map()方法创建一个新数组,并对该数组中的每个元素调用提供的函数。

  listofobjects = listofobjects.map(function(currentobject) {
       if(currentobject.keyone === targetobject.keyone){
             currentobject.keytwo = "changed value";
       }
  });

The result is the same array, but now the keytwo of the tarjetobjec has change its value. 结果是相同的数组,但是现在tarjetobjec的keytwo已更改其值。

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

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