简体   繁体   English

如何用单线替换JavaScript数组中的对象?

[英]How to replace an object in an array in JavaScript with a one-liner?

Given an array with some object: 给定一个带有一些对象的数组:

let array = [
  { name: 'bob', score: 12 },
  { name: 'Joe', score: 20 },
  { name: 'Sue', score: 25 }
]

How can I replace Joe's object in the array with this new object in a single line: 如何在一行中用这个新对象替换数组中的Joe对象:

let newScoreForJoe = { name: 'Joe', score: 21 }

I know that I can find the index of Joe's object in the array and then update it like so: 我知道我可以在数组中找到Joe对象的索引,然后像这样更新它:

let joeIndex = array.findIndex(x => x.name === newScoreForJoe.name)
array[joeIndex] = newScoreForJoe;

But is there an elegant one-liner to achieve the same thing? 但是,是否有一种优雅的单线实现同一件事?

I'm sure how elegant this will be for you but since you are trying to returm an array with the same amuount of objects, i would do this: 我确定这对您来说将有多优雅,但是由于您尝试使用相同的对象对象来限制数组,因此我将执行以下操作:

The array: 数组:

let array = [
  { name: 'bob', score: 12 },
  { name: 'Joe', score: 20 },
  { name: 'Sue', score: 25 }
]

The object: 物体:

let newScoreForJoe = { name: 'Joe', score: 21 }

The replace line: 替换行:

let joeIndex = array.map(x => x.name === newScoreForJoe.name ? newScoreForJoe : x)

您可以简单地一起消除joeIndex变量,然后执行以下操作:

array[array.findIndex(x => x.name === newScoreForJoe.name)] = newScoreForJoe;

You can try this answer. 您可以尝试此答案。 Just change the value of the object property. 只需更改对象属性的值即可。

array[1].score = 21;

You could use Array#some and assign the new object inside of the callback. 您可以使用Array#some并在回调内部分配新对象。

If no object is found, no assignment happens. 如果找不到对象,则不会发生分配。

 let array = [{ name: 'bob', score: 12 }, { name: 'Joe', score: 20 }, { name: 'Sue', score: 25 }], newScoreForJoe = { name: 'Joe',score: 21 }; array.some((a, i, aa) => (a.name === newScoreForJoe.name && (aa[i] = newScoreForJoe))); console.log(array); 

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

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