Javascript 指定给地图中的对象

Javascript 指定给地图中的对象,javascript,loops,Javascript,Loops,我想在数组映射中指定一个对象 这是我要添加到的对象数组 const arr = [ { "key": "Mike", "ref": 11800 }, { "key": "Raph", "ref": 9339 }, { "key": "Leo", "ref": 2560 }, ] 我

我想在数组映射中指定一个对象

这是我要添加到的对象数组

const arr = [
 {
  "key": "Mike",
  "ref": 11800
 },
 {
  "key": "Raph",
  "ref": 9339
 },
 {
  "key": "Leo",
  "ref": 2560
 },
]
我想向名为
slug
的对象添加一个新属性,同时像下面那样循环它。可能
map
不是此处使用的正确函数,因为
ESLINT
抱怨在map内分配

arr.map((item) => {
  ...item,
  item.slug = `${item.key.toLowerCase();}/${String(item.ref)}`
});

当对数组进行变异或执行有副作用的操作时,应使用
for
循环或
array.prototype.forEach
方法。如果要对数组执行纯功能操作,请使用
array.prototype.filter
array.prototype.map
,等等

如果要在现有数组元素上设置新属性,请执行以下操作:

const arr = [ { key: "Mike", ref: 11800 }, /*etc*/ ];

for( const e of arr ) {
    e.slug = e.key.toLowerCase() + "/" + e.ref.toString();
} 
const arr = [ { key: "Mike", ref: 11800 }, /*etc*/ ];

// Note the parentheses within `map` to avoid ambiguous syntax:
const newArr = arr.map( e => ( { slug: e.key.toLowerCase() + "/" + e.ref.toString() } ) );

console.log( newArr ); // [ { slug: "mike/11800" } ]
如果要生成包含新成员的新数组,请执行以下操作:

const arr = [ { key: "Mike", ref: 11800 }, /*etc*/ ];

for( const e of arr ) {
    e.slug = e.key.toLowerCase() + "/" + e.ref.toString();
} 
const arr = [ { key: "Mike", ref: 11800 }, /*etc*/ ];

// Note the parentheses within `map` to avoid ambiguous syntax:
const newArr = arr.map( e => ( { slug: e.key.toLowerCase() + "/" + e.ref.toString() } ) );

console.log( newArr ); // [ { slug: "mike/11800" } ]
或者,要复制所有属性,然后添加新属性,请使用
Object.assign

const arr = [ { key: "Mike", ref: 11800 }, /*etc*/ ];

const newArr = arr.map( e => Object.assign( {}, e, { slug: e.key.toLowerCase() + "/" + e.ref.toString() } ) );

console.log( newArr ); // [ { key: "Mike", ref: 11800, slug: "mike/11800" } ]
.map()返回一个新数组,其中包含为每个元素调用提供的函数的结果,因此应将其分配给新变量:

const arr=[{
“钥匙”:“迈克”,
“参考”:11800
},
{
“键”:“Raph”,
“参考”:9339
},
{
“钥匙”:“狮子座”,
“参考”:2560
},
]
const newArr=arr.map(项=>({
…项目,
slug:`${item.key.toLowerCase()}/${String(item.ref)}`
}))

console.dir(newArr)
回调传递到
Array
的函数方法,如
map
filter
不应该有副作用,因此ESLINT警告。这是用于Redux Reducer函数的吗?而不是
item.slug=
也许您想要
slug:
?在创建新对象属性后,将
item.slug=
更改为
slug:
。另外,将
{}
括在括号
({})
中,这样它就不会被解释为函数体,而是被解释为对象literal@NickParsonsOP说他们想在现有的
项上设置
.slug
,而不是返回一个新对象。我想OP应该会澄清这一点。如果map是右边的函数,它也需要在左边赋值
let newArr=arr.map(…etc