Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/458.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 操纵数组的对象属性_Javascript - Fatal编程技术网

Javascript 操纵数组的对象属性

Javascript 操纵数组的对象属性,javascript,Javascript,我有一个具有某些属性的对象数组。我想对object属性进行一些计算,并期望返回一个数组 我试过了,似乎不管用 array.map(el => { el.count * 2; return el }) 期望 array = [{ count: 8, string: 'randomstring' }, { count: 18, string: 'randomstring' }, { count: 14, string: 'ran

我有一个具有某些属性的对象数组。我想对object属性进行一些计算,并期望返回一个数组

我试过了,似乎不管用

array.map(el => {
    el.count * 2;
    return el
})
期望

array = [{
    count: 8,
    string: 'randomstring'
}, {
    count: 18,
    string: 'randomstring'
}, {
    count: 14,
    string: 'randomstring'
}, {
    count: 24,
    string: 'randomstring'
}]

el.count*2
不会更改el.count的值。您可以将其指定为

el.count = el.count * 2;
但这将产生另一个问题。它将更改原始数据。因此,最好使用

let array=[{count:4,string:'randomstring'},{count:9,string:'randomstring'},{count:7,string:'randomstring'},{count:12,string:'randomstring'}]
设res=array.map(el=>({…el,count:el.count*2}));

控制台日志(res)您可以映射独立对象,而无需改变原始数组

newArray = array.map(o => Object.assign({}, o, { count: o.count * 2 }));
同样的方法也适用于传播对象

newArray = array.map(o => ({ ...o, count: o.count * 2 }));

没有显式地改变对象的值(这就是为什么我们首先使用map、filter和reduce):

试一试

let数组=[
{count:4,string:'randomstring'},
{count:9,string:'randomstring'},
{count:7,string:'randomstring'},
{计数:12,字符串:'randomstring'}
];
设r=array.map(e=>(e.count*=2,e))

控制台日志(r)尝试<代码>el.count*=2。你没有设置它。你甚至不需要
地图。这可以通过使用
forEach
来实现。我将以拼写错误结束这个问题。它可能是拼写错误,但可能是缺乏理解。不清楚它是哪一个。这是一个缺乏理解的问题。注意,这种方式会使原始对象发生变异。是的,当然-但OP没有提到有疑问的不可变对象,但这不是
map()
的正确用法。预计
map()
不会更改实际数据
map()
不用于更改原始数组。哦-我不知道-你能在ecma/js规范中提供正确的链接吗?我不是说它不能使用。我的意思是它不应该这样使用。为此,
forEach
是最好的选择。
newArray = array.map(o => ({ ...o, count: o.count * 2 }));
array.map(({ count, string }) => (
   { count: count * 2, string }
));
array.map(e=>(e.count*=2,e))