简体   繁体   English

修改数组内的对象而不使用循环

[英]Modify object inside array without using loop

Is there any way in javascript which can modify array value. javascript中有什么方法可以修改数组值。 I have done it by using for loop and there is another method call forEach . 我已经通过使用for loop完成了,还有另一个方法调用forEach I wanted to get it done by using only one line. 我只想用一行就可以完成。 Like I have seen code for converting onject into array by using Array.prototype.slice . 就像我看到的代码一样,可以使用Array.prototype.slice将onject转换为数组。 So can we get the requirement done by using similar function. 因此,我们可以通过使用类似的函数来完成要求。 I google it but did not find any relevant post. 我用谷歌搜索,但没有找到任何相关的帖子。

this.gome = (function(data){
        for(var i=0;i<data.length;i++){
          data[i].id = i
        }
        return data })(data.gome);

this.gome = Array.prototype.slice.call(data.gome,//code) // something like that.

map is your friend: map是你的朋友:

this.gome = data.gome.map((x, i) => ({...x, id: i}));

Or without ES2016 : 或不带ES2016:

this.gome = data.gome.map((x, i) => Object.assign({}, x, {id: i }));

这将用一行添加值,尽管它仍然是for循环

for(var i = 0, l = data.length; i<l; i++){ data[i].id = i };

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

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